codasift 0.1.0__cp313-cp313-win_amd64.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.
codasift/__init__.py ADDED
File without changes
@@ -0,0 +1,3 @@
1
+ """
2
+ Codasift Core Subpackage.
3
+ """
@@ -0,0 +1,42 @@
1
+ from codasift.languages.base import BaseLanguage
2
+ from codasift.languages.python import PythonLanguage
3
+
4
+ # Central registry of language plugins — add new language instances here
5
+ REGISTERED_LANGUAGES: list[BaseLanguage] = [
6
+ PythonLanguage(),
7
+ ]
8
+
9
+
10
+ def get_supported_languages() -> list[BaseLanguage]:
11
+ """Returns the list of all registered language plugins."""
12
+ return list(REGISTERED_LANGUAGES)
13
+
14
+
15
+ def detect_language(project_path: str) -> BaseLanguage | None:
16
+ """Returns the first registered language plugin that matches the project."""
17
+ for language in REGISTERED_LANGUAGES:
18
+ if language.detect(project_path):
19
+ return language
20
+ return None
21
+
22
+
23
+ def get_language_for_file(file_path: str) -> BaseLanguage | None:
24
+ """Returns the language plugin responsible for a given file path based on extension."""
25
+ for language in REGISTERED_LANGUAGES:
26
+ if language.is_supported_file(file_path):
27
+ return language
28
+ return None
29
+
30
+
31
+ def get_supported_language_names() -> list[str]:
32
+ """Returns the names of all currently registered languages."""
33
+ return [lang.name for lang in REGISTERED_LANGUAGES]
34
+
35
+
36
+ def get_supported_extensions() -> list[str]:
37
+ """Returns all file extensions handled across all registered languages."""
38
+ exts: list[str] = []
39
+ for lang in REGISTERED_LANGUAGES:
40
+ exts.extend(getattr(lang, "file_extensions", []))
41
+ return exts
42
+
codasift/main.py ADDED
@@ -0,0 +1,923 @@
1
+ import os
2
+ import sys
3
+ from typing import Optional, Dict, Any, List
4
+ import typer
5
+ from codasift.core.terminal_utils import enable_safe_terminal_output
6
+
7
+ enable_safe_terminal_output()
8
+ from codasift.core.scanner import scan
9
+ from codasift.core.exporter import export as run_export
10
+ from codasift.core.licensing import (
11
+ ensure_project_limit_allows,
12
+ has_pro_license,
13
+ LicenseLimitError,
14
+ )
15
+
16
+ from codasift.core.constants import get_api_url, get_frontend_url
17
+
18
+ app = typer.Typer(help="Codasift — Real-time AST code context layer for AI coding assistants.")
19
+
20
+
21
+ def _check_and_display_terms_notice() -> None:
22
+ """
23
+ Displays a non-intrusive first-run shrink-wrap acceptance notice and records acknowledgment.
24
+ Ensures users installing directly via pip/package managers receive contractual notice.
25
+ """
26
+ try:
27
+ from codasift.core.config_cli import get_global_state, save_global_state
28
+ state = get_global_state()
29
+ current_terms_ver = "2026.1"
30
+ if state.get("accepted_terms_version") != current_terms_ver:
31
+ typer.secho(
32
+ "[Codasift] By using this software, you agree to our Terms of Service "
33
+ f"({get_frontend_url()}/terms) and Privacy Policy ({get_frontend_url()}/privacy). "
34
+ "If you do not agree, you must discontinue use immediately.",
35
+ fg=typer.colors.CYAN,
36
+ dim=True,
37
+ err=True,
38
+ )
39
+ state["accepted_terms_version"] = current_terms_ver
40
+ save_global_state(state)
41
+ except Exception:
42
+ pass
43
+
44
+
45
+ def version_callback(value: bool) -> None:
46
+ if value:
47
+ typer.echo("codasift 0.1.0")
48
+ raise typer.Exit()
49
+
50
+
51
+ @app.callback()
52
+ def main_callback(version: Optional[bool] = typer.Option(None, "--version", "-v", help="Show version and exit.",
53
+ callback=version_callback, is_eager=True,)) -> None:
54
+ """Codasift CLI global callback."""
55
+ _check_and_display_terms_notice()
56
+ try:
57
+ from codasift.core.licensing import flush_pending_cloud_deactivations
58
+ flush_pending_cloud_deactivations()
59
+ except Exception:
60
+ pass
61
+
62
+
63
+ def _check_limits_and_exit_if_failed(project_path: str) -> None:
64
+ try:
65
+ ensure_project_limit_allows(project_path)
66
+ except LicenseLimitError as e:
67
+ typer.echo(err=True)
68
+ typer.secho("[Warning] Free Tier Limit Reached", fg=typer.colors.YELLOW, bold=True, err=True)
69
+
70
+ typer.secho("You are trying to run Codasift in a new project: ", nl=False, err=True)
71
+ typer.secho(e.current_project, fg=typer.colors.CYAN, bold=True, err=True)
72
+
73
+ typer.secho("Currently active project: ", nl=False, err=True)
74
+ typer.secho(e.active_project, fg=typer.colors.WHITE, dim=True, err=True)
75
+
76
+ typer.echo(err=True)
77
+ typer.secho("Please purchase Codasift Local Pro ($20 one-time) to unlock unlimited projects:", fg=typer.colors.GREEN, err=True)
78
+ typer.secho(f"{get_frontend_url()}/pricing", fg=typer.colors.CYAN, underline=True, bold=True, err=True)
79
+
80
+ typer.echo(err=True)
81
+ typer.secho("Or activate your license key:", fg=typer.colors.GREEN, err=True)
82
+ typer.secho("codasift activate <KEY>", fg=typer.colors.CYAN, bold=True, err=True)
83
+ typer.echo(err=True)
84
+ raise typer.Exit(code=1)
85
+
86
+
87
+ def _format_clean_error(e: Exception, fallback: str = "An unexpected error occurred.") -> str:
88
+ """Format an exception into a clean user message, suppressing internal traceback leakage."""
89
+ msg = str(e).strip()
90
+ if not msg or "Traceback (most recent call last)" in msg or "File \"" in msg:
91
+ return fallback
92
+ return msg
93
+
94
+
95
+
96
+ @app.command()
97
+ def init(
98
+ path: str = typer.Argument(default=".", help="Path to the project folder to scan."),
99
+ output: Optional[str] = typer.Option(None, "--output", "-o", help="Output file path (default: codasift_context.md)."),
100
+ compact: bool = typer.Option(False, "--compact", help="Generate high-density compact context file optimized for LLM token windows."),
101
+ ):
102
+ """
103
+ Scan a project folder and generate a context file.
104
+ """
105
+ import os
106
+ import sys
107
+ from codasift.core.exporter import resolve_context_output_path
108
+ from codasift.core.config_cli import get_project_output_path, save_project_output_path
109
+ project_path = os.path.abspath(path or ".")
110
+
111
+ # Enforce local active project limits
112
+ _check_limits_and_exit_if_failed(project_path)
113
+
114
+ # Resolve output path non-destructively with preference persistence
115
+ is_explicit_override = bool(output)
116
+ if not output:
117
+ from codasift.core.config_cli import has_saved_project_output_path
118
+ if has_saved_project_output_path(project_path):
119
+ # Workspace already configured: use last saved md file directly without prompting
120
+ saved_output = get_project_output_path(project_path)
121
+ output = os.path.join(project_path, saved_output) if not os.path.isabs(saved_output) else saved_output
122
+ else:
123
+ # First time in unconfigured workspace: check if default file exists
124
+ default_target = get_project_output_path(project_path)
125
+ target_candidate = os.path.join(project_path, default_target)
126
+ if os.path.exists(target_candidate):
127
+ is_interactive = (
128
+ sys.stdin.isatty()
129
+ or "click" in getattr(type(sys.stdin), "__module__", "")
130
+ or os.environ.get("PYTEST_CURRENT_TEST") is not None
131
+ )
132
+ if is_interactive:
133
+ typer.secho(f"\n[NOTICE] Existing context file '{default_target}' detected.", fg=typer.colors.YELLOW, bold=True)
134
+ overwrite = typer.confirm(f"Do you want to overwrite '{default_target}'?", default=True)
135
+ if overwrite:
136
+ output = target_candidate
137
+ else:
138
+ resolved_output, was_renamed = resolve_context_output_path(project_path, None, default_filename=default_target)
139
+ output = resolved_output
140
+ typer.secho(f"Preserving existing file and saving as: {os.path.basename(output)}", fg=typer.colors.CYAN)
141
+ else:
142
+ resolved_output, was_renamed = resolve_context_output_path(project_path, None, default_filename=default_target)
143
+ output = resolved_output
144
+ if was_renamed:
145
+ typer.secho(f"\n[NOTICE] Existing '{default_target}' detected. Preserving it and saving as: {os.path.basename(resolved_output)}", fg=typer.colors.YELLOW, bold=True)
146
+ typer.secho(f" (Hint: Use -o {default_target} or --output <path> to overwrite or specify a custom destination)", fg=typer.colors.CYAN, dim=True)
147
+ else:
148
+ output = target_candidate
149
+ else:
150
+ resolved_output, was_renamed = resolve_context_output_path(project_path, output, default_filename="codasift_context.md")
151
+ output = resolved_output
152
+
153
+ # Persist resolved output preference into .codasift/config.json
154
+ save_project_output_path(project_path, output)
155
+ if is_explicit_override:
156
+ typer.secho(f"📌 Output target set to: {os.path.basename(output)}", fg=typer.colors.CYAN)
157
+ typer.secho(f" (Saved in .codasift/config.json for future runs unless overridden again)", fg=typer.colors.CYAN, dim=True)
158
+
159
+ typer.secho(f"Scanning project at: {project_path}", fg=typer.colors.CYAN)
160
+
161
+ description = typer.prompt(
162
+ typer.style("Briefly describe your project (press Enter to skip)", fg=typer.colors.CYAN),
163
+ default="",
164
+ show_default=False
165
+ )
166
+ description = description.strip() or "No description provided."
167
+
168
+ if not output.endswith(".md"):
169
+ typer.secho("\n[ERROR] Output file must be a .md file.", fg=typer.colors.RED, bold=True, err=True)
170
+ raise typer.Exit(code=1)
171
+
172
+ try:
173
+ typer.secho("Analysing project...", fg=typer.colors.CYAN)
174
+ result = scan(project_path, description=description)
175
+
176
+ typer.secho("Generating context file...", fg=typer.colors.CYAN)
177
+ output_path = run_export(result, output_path=output, format_type="md", compact=compact)
178
+
179
+ typer.secho("\n" + "=" * 56, fg=typer.colors.GREEN, bold=True)
180
+ typer.secho(" [OK] Context File Generated Successfully! ✨", fg=typer.colors.GREEN, bold=True)
181
+ typer.secho("=" * 56, fg=typer.colors.GREEN, bold=True)
182
+ typer.secho(f" Target File : {output_path}", fg=typer.colors.WHITE, bold=True)
183
+ typer.secho(f" Project : {result.get('project_name', 'Unnamed')}", fg=typer.colors.CYAN)
184
+ typer.secho(f" Language : {result.get('stack', {}).get('language', 'Unknown')}", fg=typer.colors.CYAN)
185
+ typer.secho(f" Functions : {len(result.get('functions', []))} AST symbols detected", fg=typer.colors.CYAN)
186
+ typer.secho("-" * 56, fg=typer.colors.BLACK, dim=True)
187
+ try:
188
+ from codasift.core.auth_cli import load_credentials
189
+ creds = load_credentials()
190
+ except Exception:
191
+ creds = None
192
+
193
+ if creds and creds.get("access_token"):
194
+ user_label = creds.get("email") or creds.get("user_id") or "Active"
195
+ typer.secho(f" 👤 Account : Linked ({user_label})", fg=typer.colors.CYAN)
196
+ else:
197
+ typer.secho(" 💡 Tip: Run `codasift login` to link this terminal to your", fg=typer.colors.YELLOW)
198
+ typer.secho(" web dashboard & manage machine slots.", fg=typer.colors.YELLOW)
199
+ typer.secho("=" * 56 + "\n", fg=typer.colors.GREEN, bold=True)
200
+
201
+ except RuntimeError as e:
202
+ err_text = _format_clean_error(e)
203
+ typer.secho(f"\n[ERROR] {err_text}", fg=typer.colors.RED, bold=True, err=True)
204
+
205
+ if "exceeds max" in err_text.lower() or any(keyword in err_text.lower() for keyword in ("max single file limit", "max total size", "max file limit", "max file size")):
206
+ import sys
207
+ from codasift.core.config_cli import get_project_config_path, scaffold_project_config
208
+ cfg_path = get_project_config_path(project_path)
209
+ typer.echo(err=True)
210
+ typer.secho("💡 Recovery Options:", fg=typer.colors.CYAN, bold=True, err=True)
211
+ typer.secho(" 1. Add large files or heavy directories to .codasiftignore in your project root.", fg=typer.colors.WHITE, err=True)
212
+ typer.secho(f" 2. Increase project size limits in: {cfg_path}", fg=typer.colors.WHITE, err=True)
213
+ typer.secho(" 3. Or run direct limit commands:", fg=typer.colors.WHITE, err=True)
214
+ typer.secho(" - codasift config set max_total_size 200 (Project total in MB)", fg=typer.colors.CYAN, err=True)
215
+ typer.secho(" - codasift config set max_file_size 1500 (Single file in KB)", fg=typer.colors.CYAN, err=True)
216
+ typer.secho(" - codasift config set max_files 25000 (Max file count)", fg=typer.colors.CYAN, err=True)
217
+
218
+ if sys.stdin.isatty() and not os.path.exists(cfg_path):
219
+ typer.echo(err=True)
220
+ if typer.confirm("Would you like to initialize .codasift/config.json with custom limits now?", default=True):
221
+ scaffold_project_config(project_path, force=True, custom_limits={"max_total_size_mb": 200, "max_file_size_kb": 2000})
222
+ typer.secho(f"\n[OK] Created {cfg_path} with 200MB limit.", fg=typer.colors.GREEN, bold=True)
223
+ typer.secho("Please re-run `codasift init` to scan with updated limits.\n", fg=typer.colors.CYAN, bold=True)
224
+ raise typer.Exit(code=1)
225
+
226
+ except Exception as e:
227
+ clean_msg = _format_clean_error(e, fallback="An unexpected error occurred during context generation.")
228
+ typer.secho(f"\n[ERROR] {clean_msg}", fg=typer.colors.RED, bold=True, err=True)
229
+ raise typer.Exit(code=1)
230
+
231
+
232
+
233
+
234
+ @app.command()
235
+ def demo(
236
+ path: str = typer.Option("./codasift-demo", "--path", "-p", hidden=True, help="Directory where demo sandbox will be created."),
237
+ force: bool = typer.Option(False, "--force", "-f", help="Overwrite demo directory if it already exists.")
238
+ ):
239
+ """
240
+ Scaffold a sandbox demo project and run an instant first scan (<30s Time-to-Value).
241
+ Always scaffolds strictly into the 'codasift-demo' sandbox folder by default.
242
+ """
243
+ import os
244
+ import shutil
245
+
246
+ demo_dir = os.path.abspath(path or "codasift-demo")
247
+ dir_name = os.path.basename(demo_dir)
248
+ if os.path.exists(demo_dir):
249
+ if not force and sys.stdin.isatty():
250
+ confirm = typer.confirm(f"Directory '{dir_name}' already exists. Overwrite with fresh demo files?", default=True)
251
+ if not confirm:
252
+ typer.secho("Demo setup cancelled.", fg=typer.colors.YELLOW)
253
+ raise typer.Exit(code=0)
254
+ shutil.rmtree(demo_dir, ignore_errors=True)
255
+
256
+ os.makedirs(os.path.join(demo_dir, "src"), exist_ok=True)
257
+
258
+ # Generate cryptographic machine-bound demo marker
259
+ from codasift.core.licensing import create_demo_marker
260
+ create_demo_marker(demo_dir)
261
+
262
+ # 1. Sample auth service (multi-branch functions with decorators & type hints)
263
+ auth_service_code = '''"""
264
+ Sample Authentication Service for Codasift Demo.
265
+ Demonstrates AST function extraction, dependency signatures, and type annotations.
266
+ """
267
+ from typing import Optional, Dict, Any
268
+ from functools import wraps
269
+
270
+ def rate_limited(limit_per_minute: int = 60):
271
+ """Decorator to simulate rate-limiting middleware."""
272
+ def decorator(fn):
273
+ @wraps(fn)
274
+ def wrapper(*args, **kwargs):
275
+ return fn(*args, **kwargs)
276
+ return wrapper
277
+ return decorator
278
+
279
+ class AuthService:
280
+ def __init__(self, token_secret: str = "demo-secret"):
281
+ self.secret = token_secret
282
+ self.sessions: Dict[str, Dict[str, Any]] = {}
283
+
284
+ @rate_limited(limit_per_minute=120)
285
+ def authenticate_user(self, username: str, password_hash: str) -> Optional[Dict[str, Any]]:
286
+ """Verify user credentials and establish session context."""
287
+ if not username or not password_hash:
288
+ return None
289
+ session = {"user": username, "role": "developer", "tier": "pro"}
290
+ self.sessions[username] = session
291
+ return session
292
+
293
+ def revoke_session(self, username: str) -> bool:
294
+ """Invalidate active developer session."""
295
+ return self.sessions.pop(username, None) is not None
296
+ '''
297
+ with open(os.path.join(demo_dir, "src", "auth_service.py"), "w", encoding="utf-8") as f:
298
+ f.write(auth_service_code.strip() + "\n")
299
+
300
+ # 2. Sample data pipeline (async stream processor)
301
+ data_pipeline_code = '''"""
302
+ Async Data Pipeline Simulation for Codasift Demo.
303
+ Demonstrates asynchronous generator parsing, error classification, and stream flow.
304
+ """
305
+ import asyncio
306
+ from typing import AsyncGenerator, List, Dict
307
+
308
+ async def stream_telemetry_events(batch_size: int = 50) -> AsyncGenerator[List[Dict[str, float]], None]:
309
+ """Simulate streaming telemetry metrics from edge workers."""
310
+ for step in range(3):
311
+ await asyncio.sleep(0.01)
312
+ yield [{"metric_id": float(step * 10 + i), "latency_ms": 1.25 * i} for i in range(batch_size)]
313
+
314
+ def compute_percentiles(samples: List[float], p95: bool = True) -> float:
315
+ """Calculate latency distribution summary."""
316
+ if not samples:
317
+ return 0.0
318
+ sorted_samples = sorted(samples)
319
+ idx = int(len(sorted_samples) * 0.95) if p95 else int(len(sorted_samples) * 0.50)
320
+ return sorted_samples[min(idx, len(sorted_samples) - 1)]
321
+ '''
322
+ with open(os.path.join(demo_dir, "src", "data_pipeline.py"), "w", encoding="utf-8") as f:
323
+ f.write(data_pipeline_code.strip() + "\n")
324
+
325
+ # 3. Quickstart README
326
+ readme_content = '''# Codasift Sandbox Demo 🚀
327
+
328
+ Welcome to your rapid-evaluation sandbox project!
329
+
330
+ ## 30-Second First Run
331
+ 1. Start the live file watcher:
332
+ ```bash
333
+ codasift watch
334
+ ```
335
+ 2. Open `src/auth_service.py` in your favorite editor.
336
+ 3. Add a new function or modify docstrings, and watch your terminal immediately summarize the AST changes with zero LLM prompt bloat!
337
+ '''
338
+ with open(os.path.join(demo_dir, "README.md"), "w", encoding="utf-8") as f:
339
+ f.write(readme_content.strip() + "\n")
340
+
341
+ typer.secho("\n✨ Codasift Demo Sandbox Created Successfully!", fg=typer.colors.GREEN, bold=True)
342
+ typer.secho(f"Location: {demo_dir}", fg=typer.colors.CYAN)
343
+ typer.secho("Running initial AST scan on demo code...", fg=typer.colors.CYAN)
344
+
345
+ result = scan(demo_dir, description="Codasift Sandbox Starter Demo")
346
+ out_file = os.path.join(demo_dir, "codasift_context.md")
347
+ run_export(result, output_path=out_file, format_type="md")
348
+
349
+ typer.secho("\n" + "=" * 56, fg=typer.colors.GREEN, bold=True)
350
+ typer.secho(" [OK] Initial Demo Scan Complete! ✨", fg=typer.colors.GREEN, bold=True)
351
+ typer.secho("=" * 56, fg=typer.colors.GREEN, bold=True)
352
+ typer.secho(f" Demo Path : {demo_dir}", fg=typer.colors.WHITE, bold=True)
353
+ typer.secho(f" Context File: {out_file}", fg=typer.colors.CYAN)
354
+ typer.secho(f" AST Symbols : {len(result.get('functions', []))} functions discovered", fg=typer.colors.CYAN)
355
+ typer.secho(" Next Steps:", fg=typer.colors.WHITE, bold=True)
356
+ typer.secho(" 1. cd codasift-demo", fg=typer.colors.CYAN)
357
+ typer.secho(" 2. codasift watch", fg=typer.colors.CYAN)
358
+ typer.secho(" 3. Edit src/auth_service.py to see real-time AST diffing!", fg=typer.colors.CYAN)
359
+ typer.secho("-" * 56, fg=typer.colors.BLACK, dim=True)
360
+ try:
361
+ from codasift.core.auth_cli import load_credentials
362
+ creds = load_credentials()
363
+ except Exception:
364
+ creds = None
365
+
366
+ if creds and creds.get("access_token"):
367
+ user_label = creds.get("email") or creds.get("user_id") or "Active"
368
+ typer.secho(f" 👤 Account : Linked ({user_label})", fg=typer.colors.CYAN)
369
+ else:
370
+ typer.secho(" 💡 Tip: Run `codasift login` to link this terminal to your", fg=typer.colors.YELLOW)
371
+ typer.secho(" web dashboard & manage machine slots.", fg=typer.colors.YELLOW)
372
+ typer.secho("=" * 56 + "\n", fg=typer.colors.GREEN, bold=True)
373
+
374
+
375
+ @app.command()
376
+ def watch(
377
+ path: str = typer.Argument(default=".", help="Path to the project folder to watch."),
378
+ output: Optional[str] = typer.Option(None, "--output", "-o", help="Output file path (default: codasift_context.md or configured path)."),
379
+ debounce: float = typer.Option(1.0, "--debounce", "-d", help="Debounce delay in seconds."),
380
+ provider: str = typer.Option(None, "--provider", "-p", help="AI provider override ('ollama' or 'gemini')."),
381
+ model: str = typer.Option(None, "--model", "-m", help="AI model override (e.g. 'gemini-3.7-flash')."),
382
+ gemini_key: str = typer.Option(None, "--gemini-key", "-k", help="Google Gemini API key for this session."),
383
+ ):
384
+ """
385
+ Start a background watcher that updates the context file automatically when files change.
386
+ """
387
+ import os
388
+ import time
389
+ from watchdog.observers import Observer
390
+ from codasift.core.watcher import WorkspaceStateManager, DebouncedEventHandler
391
+
392
+ project_path = os.path.abspath(path or ".")
393
+
394
+ # Enforce local active project limits
395
+ _check_limits_and_exit_if_failed(project_path)
396
+
397
+ # Resolve output path: uses last saved md file from config unless explicitly specified
398
+ if not output:
399
+ from codasift.core.config_cli import get_project_output_path
400
+ output = get_project_output_path(project_path)
401
+ else:
402
+ from codasift.core.config_cli import save_project_output_path
403
+ save_project_output_path(project_path, output)
404
+ typer.secho(f"📌 Output target set to: {os.path.basename(output)}", fg=typer.colors.CYAN)
405
+ typer.secho(f" (Saved in .codasift/config.json for future runs unless overridden again)", fg=typer.colors.CYAN, dim=True)
406
+
407
+ # Resolve output path relative to project path if not absolute
408
+ if not os.path.isabs(output):
409
+ output = os.path.join(project_path, output)
410
+
411
+ from codasift.core.config_cli import resolve_ai_provider, resolve_ai_model, resolve_gemini_api_key
412
+ from codasift.core.ai_client import is_ollama_reachable
413
+
414
+ eff_provider = resolve_ai_provider(provider, project_path)
415
+ eff_model = resolve_ai_model(model, eff_provider, project_path) or "(Default)"
416
+
417
+ typer.secho(f"Starting Codasift Watcher for: {project_path}", fg=typer.colors.CYAN)
418
+ typer.secho(f"Output target: {output}", fg=typer.colors.WHITE, dim=True)
419
+ typer.secho(f"Debounce delay: {debounce}s", fg=typer.colors.WHITE, dim=True)
420
+ if eff_provider == "ollama":
421
+ online = is_ollama_reachable()
422
+ status_text = "Online" if online else "Offline"
423
+ status_fg = typer.colors.GREEN if online else typer.colors.YELLOW
424
+ typer.secho(f"AI Engine: OLLAMA ({eff_model}) [", nl=False, fg=typer.colors.CYAN, bold=True)
425
+ typer.secho(status_text, nl=False, fg=status_fg, bold=True)
426
+ typer.secho("]", fg=typer.colors.CYAN, bold=True)
427
+ if not online:
428
+ typer.secho("💡 Note: Run 'ollama serve' to enable real-time diff summaries.", fg=typer.colors.WHITE, dim=True)
429
+ else:
430
+ has_key = bool(resolve_gemini_api_key(gemini_key, project_path))
431
+ status_text = "Active" if has_key else "Missing Key"
432
+ status_fg = typer.colors.GREEN if has_key else typer.colors.YELLOW
433
+ typer.secho(f"AI Engine: GEMINI ({eff_model}) [", nl=False, fg=typer.colors.GREEN, bold=True)
434
+ typer.secho(status_text, nl=False, fg=status_fg, bold=True)
435
+ typer.secho("]", fg=typer.colors.GREEN, bold=True)
436
+ if not has_key:
437
+ typer.secho("💡 Note: Run 'codasift config set gemini_key <KEY>' to enable Gemini AI.", fg=typer.colors.WHITE, dim=True)
438
+
439
+ try:
440
+ state_manager = WorkspaceStateManager(
441
+ project_path,
442
+ output_path=output,
443
+ cli_provider=provider,
444
+ cli_model=model,
445
+ cli_gemini_key=gemini_key,
446
+ )
447
+ event_handler = DebouncedEventHandler(state_manager, debounce_seconds=debounce)
448
+
449
+ observer = Observer()
450
+ observer.schedule(event_handler, path=state_manager.project_path, recursive=True)
451
+ observer.start()
452
+
453
+ def is_obs_alive() -> bool:
454
+ return observer.is_alive()
455
+
456
+ def restart_obs() -> None:
457
+ nonlocal observer
458
+ try:
459
+ observer.stop()
460
+ except Exception:
461
+ pass
462
+ observer = Observer()
463
+ observer.schedule(event_handler, path=state_manager.project_path, recursive=True)
464
+ observer.start()
465
+ state_manager.rebuild_meta()
466
+ state_manager.commit_changes()
467
+
468
+ from codasift.core.self_healing import ObserverHealthMonitor
469
+ obs_sentinel = ObserverHealthMonitor(is_obs_alive, restart_obs, interval_seconds=15.0)
470
+ obs_sentinel.start()
471
+
472
+ typer.secho("[OK] Watching directory. Press Ctrl+C to stop.", fg=typer.colors.GREEN, bold=True)
473
+ try:
474
+ while True:
475
+ time.sleep(1)
476
+ except KeyboardInterrupt:
477
+ typer.secho("\nStopping watcher...", fg=typer.colors.YELLOW)
478
+ obs_sentinel.stop()
479
+ state_manager.stop()
480
+ observer.stop()
481
+ observer.join()
482
+ typer.secho("[OK] Watcher stopped.", fg=typer.colors.GREEN, bold=True)
483
+
484
+ except Exception as e:
485
+ typer.secho(f"\n[ERROR] Watcher error: {e}", fg=typer.colors.RED, bold=True, err=True)
486
+ raise typer.Exit(code=1)
487
+
488
+
489
+ config_app = typer.Typer(
490
+ help="Manage project limits, AI models, and BYOK keys (subcommands: get, set, init, -i).",
491
+ invoke_without_command=True
492
+ )
493
+ app.add_typer(config_app, name="config")
494
+
495
+
496
+ @config_app.callback(invoke_without_command=True)
497
+ def config_callback(
498
+ ctx: typer.Context,
499
+ interactive: bool = typer.Option(False, "--interactive", "-i", help="Run interactive configuration wizard."),
500
+ init_flag: bool = typer.Option(False, "--init", help="Scaffold a new .codasift/config.json in project root."),
501
+ key: Optional[str] = typer.Option(None, "--key", "-k", help="Configure Google Gemini API key in secure global state."),
502
+ provider: Optional[str] = typer.Option(None, "--provider", "-p", help="Set active AI provider ('ollama' or 'gemini')."),
503
+ model: Optional[str] = typer.Option(None, "--model", "-m", help="Set default AI model (e.g. 'gemini-3.8-flash' or 'qwen2.5-coder:1.5b')."),
504
+ path: str = typer.Option(".", "--path", help="Path to project directory for local context."),
505
+ ):
506
+ """
507
+ Manage Codasift project limits, ignore configuration, AI providers, and BYOK keys.
508
+ """
509
+ import os
510
+ from codasift.core.config_cli import (
511
+ set_global_gemini_key,
512
+ set_global_provider,
513
+ set_global_model,
514
+ get_global_state,
515
+ get_full_configuration,
516
+ resolve_ai_provider,
517
+ get_project_config_path,
518
+ scaffold_project_config,
519
+ update_project_ai_provider,
520
+ update_project_ai_model,
521
+ run_interactive_config_wizard,
522
+ )
523
+ from codasift.core.config_manager import get_available_gemini_models
524
+
525
+ if ctx.invoked_subcommand is not None:
526
+ return
527
+
528
+ project_path = os.path.abspath(path)
529
+
530
+ if interactive:
531
+ run_interactive_config_wizard(project_path)
532
+ return
533
+
534
+ actions_performed = False
535
+
536
+ if init_flag:
537
+ target = get_project_config_path(project_path)
538
+ if os.path.exists(target):
539
+ confirm = typer.confirm(f"A configuration file already exists at {target}. Overwrite with default template?", default=False)
540
+ if not confirm:
541
+ typer.secho("\n[CANCELLED] Existing configuration preserved.", fg=typer.colors.YELLOW)
542
+ raise typer.Exit(code=0)
543
+ scaffold_project_config(project_path, force=True)
544
+ typer.secho(f"\n[OK] Project configuration initialized successfully!", fg=typer.colors.GREEN, bold=True)
545
+ typer.secho(f" Config File : {target}", fg=typer.colors.WHITE, bold=True)
546
+ actions_performed = True
547
+
548
+ if key:
549
+ try:
550
+ set_global_gemini_key(key)
551
+ typer.secho("\n[OK] Google Gemini API key saved to global secure state.", fg=typer.colors.GREEN, bold=True)
552
+ actions_performed = True
553
+ except Exception as e:
554
+ typer.secho(f"\n[ERROR] Failed to save Gemini key: {e}", fg=typer.colors.RED, bold=True, err=True)
555
+ raise typer.Exit(code=1)
556
+
557
+ target_project_cfg = get_project_config_path(project_path)
558
+ has_project_file = os.path.exists(target_project_cfg)
559
+
560
+ if provider:
561
+ try:
562
+ if has_project_file:
563
+ p = update_project_ai_provider(project_path, provider)
564
+ typer.secho(f"\n[OK] Default AI provider set to: {p} (project: {target_project_cfg})", fg=typer.colors.GREEN, bold=True)
565
+ else:
566
+ p = set_global_provider(provider)
567
+ typer.secho(f"\n[OK] Default AI provider set to: {p}", fg=typer.colors.GREEN, bold=True)
568
+ actions_performed = True
569
+ except Exception as e:
570
+ typer.secho(f"\n[ERROR] {e}", fg=typer.colors.RED, bold=True, err=True)
571
+ raise typer.Exit(code=1)
572
+
573
+ if model:
574
+ try:
575
+ if provider:
576
+ active_p = provider.strip().lower()
577
+ elif has_project_file:
578
+ active_p = resolve_ai_provider(None, project_path)
579
+ else:
580
+ active_p = get_global_state().get("provider") or "ollama"
581
+
582
+ if active_p == "local":
583
+ active_p = "ollama"
584
+ if has_project_file:
585
+ m = update_project_ai_model(project_path, model, provider=active_p)
586
+ provider_title = "Ollama" if active_p == "ollama" else "Gemini"
587
+ typer.secho(f"\n[OK] Default {provider_title} model set to: {m} (project: {target_project_cfg})", fg=typer.colors.GREEN, bold=True)
588
+ else:
589
+ m = set_global_model(model, provider=active_p)
590
+ provider_title = "Ollama" if active_p == "ollama" else "Gemini"
591
+ typer.secho(f"\n[OK] Default {provider_title} model set to: {m}", fg=typer.colors.GREEN, bold=True)
592
+ actions_performed = True
593
+ except Exception as e:
594
+ typer.secho(f"\n[ERROR] {e}", fg=typer.colors.RED, bold=True, err=True)
595
+ raise typer.Exit(code=1)
596
+
597
+ if not actions_performed:
598
+ cfg = get_full_configuration(project_path)
599
+ typer.echo()
600
+ typer.secho("+------------------------------------------------------------------------+", fg=typer.colors.CYAN)
601
+ typer.secho("| Codasift Project & AI Configuration |", fg=typer.colors.CYAN, bold=True)
602
+ typer.secho("+------------------------------------------------------------------------+", fg=typer.colors.CYAN)
603
+
604
+ # Project configuration section
605
+ config_status = "Custom File Active" if cfg.get("has_project_config") else "Using Built-in Defaults"
606
+ typer.secho(f" Project Config File : {cfg.get('project_config_path')}", fg=typer.colors.WHITE)
607
+ typer.secho(f" Configuration Status: ", nl=False)
608
+ typer.secho(f"{config_status}", fg=typer.colors.GREEN if cfg.get("has_project_config") else typer.colors.YELLOW, bold=True)
609
+
610
+ limits = cfg.get("limits", {})
611
+ typer.secho(f" Max Total Size : {limits.get('max_total_size_mb', 50)} MB")
612
+ typer.secho(f" Max Single File Size: {limits.get('max_file_size_kb', 500)} KB")
613
+ typer.secho(f" Max Scanned Files : {limits.get('max_files', 10000)} files")
614
+ typer.secho(f" Large File Policy : {cfg.get('large_file_policy', 'skeleton')} (skeleton / skip / force_full)")
615
+ typer.echo()
616
+
617
+ # AI Engine section
618
+ typer.secho("AI Engine & Providers:", fg=typer.colors.WHITE, bold=True)
619
+ typer.secho(f" Active Provider : ", nl=False)
620
+ typer.secho(f"{cfg['provider'].upper()} ", fg=typer.colors.GREEN if cfg['provider'] == 'gemini' else typer.colors.CYAN, bold=True, nl=False)
621
+ typer.secho(f"[{cfg.get('provider_origin', 'Built-in Default')}]", fg=typer.colors.WHITE, dim=True)
622
+ typer.secho(f" Configured Model : {cfg['model']} ", nl=False)
623
+ typer.secho(f"[{cfg.get('model_origin', 'Built-in Default')}]", fg=typer.colors.WHITE, dim=True)
624
+ typer.secho(f" Gemini Key Masked : {cfg['gemini_api_key_masked']}")
625
+ typer.secho(f" BYOK Daily Cap : {cfg.get('byok_max_daily_calls', 50)} calls/day ", nl=False)
626
+ typer.secho(f"[{cfg.get('byok_origin', 'Built-in Default')}]", fg=typer.colors.WHITE, dim=True)
627
+ typer.secho(f" Global State File : {cfg['global_state_file']}", fg=typer.colors.WHITE, dim=True)
628
+ typer.echo()
629
+ typer.secho("Available Gemini Models:", fg=typer.colors.WHITE, bold=True)
630
+ for m in get_available_gemini_models():
631
+ tag = " (Recommended)" if m.get("recommended") else ""
632
+ typer.secho(f" • {m['id']}{tag}", fg=typer.colors.CYAN if m.get("recommended") else typer.colors.WHITE)
633
+ typer.echo()
634
+ typer.secho("Quick Commands:", fg=typer.colors.WHITE, bold=True)
635
+ typer.secho(" Interactive wizard: codasift config -i", fg=typer.colors.CYAN)
636
+ typer.secho(" Update a setting : codasift config set <key> <val> (e.g. codasift config set max_total_size 100MB)", fg=typer.colors.WHITE)
637
+ typer.secho(" Inspect a setting : codasift config get <key> (e.g. codasift config get provider)", fg=typer.colors.WHITE)
638
+ typer.secho(" Scaffold config : codasift config init", fg=typer.colors.WHITE)
639
+ typer.secho(" All options : codasift config --help", fg=typer.colors.WHITE, dim=True)
640
+ typer.echo()
641
+
642
+
643
+ @config_app.command(name="get")
644
+ def config_get_cmd(
645
+ key: str = typer.Argument(..., help="Configuration key to query (e.g. provider, model, gemini_key, max_files, path)."),
646
+ path: str = typer.Option(".", "--path", help="Path to project directory for local context."),
647
+ ):
648
+ """
649
+ Get the effective value and origin of a configuration setting.
650
+ """
651
+ import os
652
+ from codasift.core.config_cli import get_config_value
653
+ try:
654
+ canonical_key, val, origin = get_config_value(key, os.path.abspath(path))
655
+ typer.echo(f"{canonical_key} = {val} [{origin}]")
656
+ except Exception as e:
657
+ typer.secho(f"\n[ERROR] {e}", fg=typer.colors.RED, bold=True, err=True)
658
+ raise typer.Exit(code=1)
659
+
660
+
661
+ @config_app.command(name="set")
662
+ def config_set_cmd(
663
+ key: str = typer.Argument(..., help="Configuration key to set (e.g. max_total_size, max_file_size, max_files, large_file_policy, provider, model, gemini_key, max_daily_calls)."),
664
+ value: str = typer.Argument(..., help="Value to assign."),
665
+ is_global: bool = typer.Option(False, "--global", "-g", help="Persist globally (~/.codasift/global_state.json)."),
666
+ is_local: bool = typer.Option(False, "--local", "-l", help="Persist locally in project (.codasift/config.json)."),
667
+ path: str = typer.Option(".", "--path", help="Path to project directory for local context."),
668
+ ):
669
+ """
670
+ Set a configuration setting across project or global scope.
671
+ """
672
+ import os
673
+ from codasift.core.config_cli import set_config_value
674
+ scope = "global" if is_global else ("local" if is_local else "auto")
675
+ try:
676
+ canonical_key, updated_val, applied_scope = set_config_value(
677
+ key=key,
678
+ value=value,
679
+ scope=scope,
680
+ project_path=os.path.abspath(path)
681
+ )
682
+ typer.secho(f"\n[OK] Configuration updated!", fg=typer.colors.GREEN, bold=True)
683
+ typer.secho(f" Setting : {canonical_key} = {updated_val}", fg=typer.colors.WHITE)
684
+ typer.secho(f" Scope : {applied_scope}\n", fg=typer.colors.CYAN)
685
+ except Exception as e:
686
+ typer.secho(f"\n[ERROR] {e}", fg=typer.colors.RED, bold=True, err=True)
687
+ raise typer.Exit(code=1)
688
+
689
+
690
+ @config_app.command(name="init")
691
+ def config_init_cmd(
692
+ force: bool = typer.Option(False, "--force", "-f", help="Force overwrite existing configuration without prompting."),
693
+ path: str = typer.Option(".", "--path", help="Path to project directory."),
694
+ ):
695
+ """
696
+ Scaffold a new .codasift/config.json template in the project root.
697
+ """
698
+ import os
699
+ from codasift.core.config_cli import get_project_config_path, scaffold_project_config
700
+ project_path = os.path.abspath(path)
701
+ target = get_project_config_path(project_path)
702
+ if os.path.exists(target) and not force:
703
+ confirm = typer.confirm(f"A configuration file already exists at {target}. Overwrite with default template?", default=False)
704
+ if not confirm:
705
+ typer.secho("\n[CANCELLED] Existing configuration preserved.", fg=typer.colors.YELLOW)
706
+ raise typer.Exit(code=0)
707
+ scaffold_project_config(project_path, force=True)
708
+ typer.secho(f"\n[OK] Project configuration initialized successfully!", fg=typer.colors.GREEN, bold=True)
709
+ typer.secho(f" Config File : {target}\n", fg=typer.colors.WHITE, bold=True)
710
+
711
+
712
+ @app.command("activate")
713
+ def activate(
714
+ key: str = typer.Argument(..., help="Codasift Pro license key string."),
715
+ ):
716
+ """
717
+ Activate your offline Local Pro license.
718
+ """
719
+ from codasift.core.licensing import (
720
+ verify_license_key,
721
+ load_global_state,
722
+ save_global_state,
723
+ check_online_activation,
724
+ flush_pending_cloud_deactivations,
725
+ )
726
+
727
+ try:
728
+ flush_pending_cloud_deactivations()
729
+ except Exception:
730
+ pass
731
+
732
+ typer.secho("Verifying license key...", fg=typer.colors.CYAN)
733
+ resolved_api = get_api_url()
734
+ clean_key = key.strip()
735
+ payload = verify_license_key(clean_key)
736
+ if not payload:
737
+ typer.secho("[ERROR] Invalid license key signature or corrupt key format.", fg=typer.colors.RED, bold=True, err=True)
738
+ raise typer.Exit(code=1)
739
+
740
+ # Check online activation with backend to ensure machine slots aren't exceeded
741
+ if not check_online_activation(clean_key, api_base_url=resolved_api):
742
+ typer.secho("\n[ERROR] Online activation failed: Machine slot limit reached (3 active machines) or invalid key.", fg=typer.colors.RED, bold=True, err=True)
743
+ typer.secho("To free a machine slot, run `codasift deactivate` on another machine or manage devices in your dashboard.", fg=typer.colors.YELLOW)
744
+ raise typer.Exit(code=1)
745
+
746
+ state = load_global_state()
747
+ state["license_key"] = clean_key
748
+ save_global_state(state)
749
+
750
+ typer.secho("\n[OK] License activated successfully!", fg=typer.colors.GREEN, bold=True)
751
+ typer.secho(f" Owner: {payload['email']}", fg=typer.colors.CYAN)
752
+ typer.secho(f" Tier : {payload['tier'].replace('_', ' ').title()}", fg=typer.colors.CYAN)
753
+
754
+
755
+ @app.command()
756
+ def deactivate(
757
+ force: bool = typer.Option(False, "--force", "-y", help="Bypass confirmation prompt for headless/CI deactivation.")
758
+ ):
759
+ """
760
+ Deactivate local Pro license and unlink this machine slot.
761
+ """
762
+ from codasift.core.licensing import (
763
+ load_global_state,
764
+ save_global_state,
765
+ deactivate_online_license,
766
+ queue_pending_cloud_deactivation,
767
+ )
768
+ resolved_api = get_api_url()
769
+ state = load_global_state()
770
+ old_key = state.get("license_key")
771
+ old_lease = state.get("lease_token")
772
+ if not old_key:
773
+ typer.secho("No active license key found on this machine.", fg=typer.colors.YELLOW)
774
+ return
775
+
776
+ if not force and sys.stdin.isatty():
777
+ typer.secho("\n⚠️ Machine Slot Deactivation Warning", fg=typer.colors.YELLOW, bold=True)
778
+ typer.secho(" • Unlinking this machine frees the slot on your account for another workstation.", fg=typer.colors.WHITE)
779
+ typer.secho(" • Deactivation consumes 1 of your 3 monthly self-serve reallocations (per 30-day window).", fg=typer.colors.WHITE)
780
+ typer.secho(" • Tip: If you only wish to sign out of your user session on this machine,", fg=typer.colors.CYAN)
781
+ typer.secho(" use `codasift logout` instead to preserve your machine slot allocation.\n", fg=typer.colors.CYAN)
782
+ confirmed = typer.confirm("Are you sure you want to deactivate this machine?", default=False)
783
+ if not confirmed:
784
+ typer.secho("Deactivation cancelled. Machine slot preserved.", fg=typer.colors.GREEN)
785
+ return
786
+
787
+ typer.secho("Unlinking machine slot from Codasift server...", fg=typer.colors.CYAN)
788
+ online_success, online_msg = deactivate_online_license(old_key, api_base_url=resolved_api)
789
+ if online_success:
790
+ typer.secho(f"[OK] {online_msg}", fg=typer.colors.GREEN)
791
+ else:
792
+ typer.secho(f"[WARNING] {online_msg}", fg=typer.colors.YELLOW)
793
+ queue_pending_cloud_deactivation(old_key, lease_token=old_lease)
794
+ typer.secho("Cloud slot deactivation has been queued and will auto-sync once online.", fg=typer.colors.CYAN)
795
+ typer.secho("Proceeding with local license removal.", fg=typer.colors.YELLOW)
796
+
797
+ state["license_key"] = None
798
+ state["lease_token"] = None
799
+ save_global_state(state)
800
+ typer.secho("\n[OK] License deactivated successfully on this machine.", fg=typer.colors.GREEN, bold=True)
801
+
802
+
803
+ @app.command()
804
+ def export(
805
+ path: str = typer.Argument(default=".", help="Path to the project folder."),
806
+ format: str = typer.Option("md", "--format", "-f", help="Target output format (md, claude, cursor, copilot)."),
807
+ output: str = typer.Option(None, "--output", "-o", help="Custom output file path. Defaults to standard locations."),
808
+ compact: bool = typer.Option(False, "--compact", help="Generate high-density compact context file (for md format)."),
809
+ ):
810
+ """
811
+ Export the scanned project context to specialized AI tool formats.
812
+ """
813
+ import os
814
+ project_path = os.path.abspath(path or ".")
815
+
816
+ # 1. Enforce tier restrictions
817
+ if format != "md" and not has_pro_license():
818
+ typer.secho("\n[ERROR] Custom export formats (claude, cursor, copilot) require Codasift Pro.", fg=typer.colors.RED, bold=True, err=True)
819
+ typer.secho("Please purchase Local Pro ($20 one-time) to unlock all exporters:", fg=typer.colors.CYAN)
820
+ typer.secho(f"{get_frontend_url()}/pricing", fg=typer.colors.CYAN, underline=True, bold=True)
821
+ typer.secho("\nOr activate your license key using: codasift activate <KEY>", fg=typer.colors.CYAN)
822
+ raise typer.Exit(code=1)
823
+
824
+ # 2. Enforce active project limits
825
+ _check_limits_and_exit_if_failed(project_path)
826
+
827
+ # 3. Resolve default or relative output paths relative to the project directory
828
+ if not output:
829
+ from codasift.core.exporter import resolve_context_output_path
830
+ if format == "md":
831
+ from codasift.core.config_cli import get_project_output_path
832
+ default_target = get_project_output_path(project_path)
833
+ elif format == "claude":
834
+ default_target = "claude_context.xml"
835
+ elif format == "cursor":
836
+ default_target = ".cursorrules"
837
+ elif format == "copilot":
838
+ default_target = os.path.join(".github", "copilot-instructions.md")
839
+ else:
840
+ default_target = f"codasift_context.{format}"
841
+
842
+ output, was_renamed = resolve_context_output_path(project_path, None, default_filename=default_target)
843
+ if was_renamed:
844
+ typer.secho(f"\n[NOTICE] Existing '{default_target}' detected. Preserving it and saving as: {os.path.basename(output)}", fg=typer.colors.YELLOW, bold=True)
845
+ typer.secho(f" (Hint: Use -o {default_target} or --output <path> to overwrite or specify a custom destination)", fg=typer.colors.CYAN, dim=True)
846
+ elif not os.path.isabs(output):
847
+ output = os.path.join(project_path, output)
848
+
849
+ # 4. Perform scan and export
850
+ try:
851
+ typer.secho("Analysing project...", fg=typer.colors.CYAN)
852
+ result = scan(project_path, description="Exported context.")
853
+
854
+ typer.secho(f"Exporting in '{format}' format...", fg=typer.colors.CYAN)
855
+ out_file = run_export(result, output_path=output, format_type=format, compact=compact)
856
+
857
+ typer.secho(f"\n[OK] Context successfully exported to: {out_file}", fg=typer.colors.GREEN, bold=True)
858
+ except Exception as e:
859
+ clean_msg = _format_clean_error(e, fallback="An unexpected error occurred during export.")
860
+ typer.secho(f"\n[ERROR] Export failed: {clean_msg}", fg=typer.colors.RED, bold=True, err=True)
861
+ raise typer.Exit(code=1)
862
+
863
+
864
+ @app.command()
865
+ def login(
866
+ port: Optional[int] = typer.Option(None, "--port", "-p", hidden=True, help="Internal debug override for loopback port."),
867
+ ):
868
+ """
869
+ Authenticate your terminal session via browser OAuth / JWT login.
870
+ """
871
+ import os
872
+ from codasift.core.auth_cli import run_cli_login
873
+ resolved_frontend = get_frontend_url()
874
+ resolved_api = get_api_url()
875
+ success = run_cli_login(frontend_url=resolved_frontend, port=port, api_base_url=resolved_api)
876
+ if not success:
877
+ raise typer.Exit(code=1)
878
+
879
+
880
+ @app.command()
881
+ def logout():
882
+ """
883
+ Revoke active session and purge cached terminal credentials.
884
+ """
885
+ from codasift.core.auth_cli import run_cli_logout
886
+ resolved_api = get_api_url()
887
+ run_cli_logout(api_base_url=resolved_api)
888
+
889
+
890
+ @app.command(hidden=True)
891
+ def sync(
892
+ path: str = typer.Argument(default=".", help="Path to the project folder to sync."),
893
+ ):
894
+ """
895
+ Synchronize local project AST context summary with Codasift Cloud storage.
896
+ """
897
+ import os
898
+ from codasift.core.sync_cli import run_cli_sync
899
+ resolved_api = get_api_url()
900
+ success = run_cli_sync(project_path=path, api_base_url=resolved_api)
901
+ if not success:
902
+ raise typer.Exit(code=1)
903
+
904
+
905
+ @app.command(hidden=True)
906
+ def pull(
907
+ workspace_id: str = typer.Argument(..., help="Unique ID of the workspace context to pull from Codasift Cloud."),
908
+ output: Optional[str] = typer.Option(None, "--output", "-o", help="Custom output file path (e.g., codasift_context.md or my_ws.json)."),
909
+ format_type: str = typer.Option("json", "--format", "-f", help="Output format: 'json' (native AST) or 'md' (markdown context)."),
910
+ ):
911
+ """
912
+ Pull a cloud-synced workspace context snapshot and save locally as JSON or Markdown.
913
+ """
914
+ import os
915
+ from codasift.core.sync_cli import run_cli_pull
916
+ resolved_api = get_api_url()
917
+ success = run_cli_pull(workspace_id=workspace_id, output=output, format_type=format_type, api_base_url=resolved_api)
918
+ if not success:
919
+ raise typer.Exit(code=1)
920
+
921
+
922
+ if __name__ == "__main__":
923
+ app()
@@ -0,0 +1,15 @@
1
+ Metadata-Version: 2.4
2
+ Name: codasift
3
+ Version: 0.1.0
4
+ Summary: A persistent context layer for AI users.
5
+ Project-URL: Homepage, https://codasift.dev
6
+ Project-URL: Documentation, https://codasift.dev/faq
7
+ Project-URL: Terms of Service, https://codasift.dev/terms
8
+ Project-URL: Privacy Policy, https://codasift.dev/privacy
9
+ Project-URL: Bug Tracker, https://codasift.dev
10
+ Requires-Python: >=3.10
11
+ Requires-Dist: typer>=0.12.0
12
+ Requires-Dist: watchdog>=4.0.0
13
+ Requires-Dist: cryptography>=42.0.0
14
+ Requires-Dist: google-genai>=1.0.0
15
+ Dynamic: requires-python
@@ -0,0 +1,26 @@
1
+ codasift/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ codasift/main.py,sha256=uU5d6TN2Tr8ARlQbp8bSs_4TH3Ji777QZC-tSRMVICI,45632
3
+ codasift/core/__init__.py,sha256=4SJWCENCiRzV0pvJ3oFI_zPPlS0xhbtpep9vh2ay4V0,37
4
+ codasift/core/ai_client.cp313-win_amd64.pyd,sha256=B-7zcRbXLK81WaP0mon0Vz2mJYdjaKvF6UVMZDSE7IQ,129536
5
+ codasift/core/auth_cli.cp313-win_amd64.pyd,sha256=cOPNDkr-PbgVNkIoNUdeuOeTWScSzlSj5TcR5W4lgvw,168448
6
+ codasift/core/classifier.cp313-win_amd64.pyd,sha256=1x5D9gI-uit3e6gQUTfTAa2fpsSSuUdqCrsnR4NJY4E,80384
7
+ codasift/core/config_cli.cp313-win_amd64.pyd,sha256=OHE7yGgUTvq8L559IGT2ktzqETwYVYSl0_PuIH87dOg,279552
8
+ codasift/core/config_manager.cp313-win_amd64.pyd,sha256=bEFeW-NZe8NFqWs608tSS9jkwnjue6fdaL8P8m8FwKI,108032
9
+ codasift/core/constants.cp313-win_amd64.pyd,sha256=xbXVDaO_FVU4xzmlifL5DFc8ASABEAsj3_W2OGBImWs,48128
10
+ codasift/core/diff_extractor.cp313-win_amd64.pyd,sha256=d8hvZBnjxbI-OZX7Bqu6hU3TIbiAIAyr2eKevyxO5hg,95232
11
+ codasift/core/exporter.cp313-win_amd64.pyd,sha256=vO8W-VNt8_EBaCRkJY2oBCuZvOg5VLQIMNNa40idUsI,274432
12
+ codasift/core/gemini_client.cp313-win_amd64.pyd,sha256=V7_Kv_wzQ3NJX-JSlNRzPLIR4i2vdzIRQr1NED9Z8aM,111104
13
+ codasift/core/licensing.cp313-win_amd64.pyd,sha256=Yx7wgHi9Nv0klCfAS2izih5kwgZ3NKtp5uhqt64s2Qs,212992
14
+ codasift/core/scanner.cp313-win_amd64.pyd,sha256=Xcmn09fraNBCcpMupCjDhDpVMVIk7FLJEr6b0HWMG08,178688
15
+ codasift/core/self_healing.cp313-win_amd64.pyd,sha256=Yc8gRakMMbA4xIWSJiBoz9VrqkcEO15DfnZrAskeUVs,139776
16
+ codasift/core/sync_cli.cp313-win_amd64.pyd,sha256=EP6wulnOC-81GfZk60x5o_qgprsHd7zaMVcZq6asezQ,151040
17
+ codasift/core/terminal_utils.cp313-win_amd64.pyd,sha256=qL1RQpd71WI1mAXa6ah4JN1FSy_mLu4HtSuyf2RP4RU,55296
18
+ codasift/core/watcher.cp313-win_amd64.pyd,sha256=rniDxxmqZxC26k7vS9Z7lk9aIRAkJUuzLKxifJF604U,265216
19
+ codasift/languages/__init__.py,sha256=GyUN62JGLhSqXgYcRUc1r3qhy4Ig1tc07D9N5nI-3TA,1453
20
+ codasift/languages/base.cp313-win_amd64.pyd,sha256=oBzqPurFm0lyi0CIRTwnDM4Nsg-mmMTh7PMdiTp-r2g,73216
21
+ codasift/languages/python.cp313-win_amd64.pyd,sha256=rNGkelrq1cx0BlIddsgWfk9zUmatwYCSVn_p99mqvj8,263168
22
+ codasift-0.1.0.dist-info/METADATA,sha256=ZV0oeDlFYiwjhOc1iSl4Egok1rygIvq6eKwPoXJMiB8,557
23
+ codasift-0.1.0.dist-info/WHEEL,sha256=qV0EIPljj1XC_vuSatRWjn02nZIz3N1t8jsZz7HBr2U,101
24
+ codasift-0.1.0.dist-info/entry_points.txt,sha256=1L0Vu7G8Vm0sMGEQExiWXM9EvIwjYB-jy_ww55-FatQ,47
25
+ codasift-0.1.0.dist-info/top_level.txt,sha256=OWD0BEAyn_CQYEWHzUzoZRJq3Pcy7h4U3bOBFlKoCpo,9
26
+ codasift-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: false
4
+ Tag: cp313-cp313-win_amd64
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ codasift = codasift.main:app
@@ -0,0 +1 @@
1
+ codasift