-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbootstrap.py
More file actions
executable file
·5839 lines (4895 loc) · 186 KB
/
bootstrap.py
File metadata and controls
executable file
·5839 lines (4895 loc) · 186 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Gemini Workspace Framework v1.0.0
Creates, validates, and upgrades self-contained LLM workspaces.
Usage:
python bootstrap.py # Interactive mode
python bootstrap.py -t 2 -n myproject # Create Standard workspace
python bootstrap.py --validate ./myproject # Validate workspace
python bootstrap.py --upgrade ./myproject # Upgrade to next tier
Features:
- Tiered workspace system (Lite, Standard, Enterprise)
- Built-in validation and health monitoring
- Tier upgrades with backup/rollback support
- Template system for custom workspace types
Build Information:
Version: 1.0.0
Built: 2026-03-22 04:32:06 UTC
Source: Modular architecture (bootstrap_src/)
This file is AUTO-GENERATED from modular source.
DO NOT EDIT THIS FILE DIRECTLY.
Edit files in bootstrap_src/ and rebuild with: python bootstrap_src/build.py
"""
from typing import List
import os
import re
import json
import hashlib
import logging
from pathlib import Path
from datetime import datetime, timezone
from abc import ABC, abstractmethod
from typing import Dict
from typing import Optional
from dataclasses import dataclass, asdict
from typing import Any
import subprocess
import sys
from functools import lru_cache
import shutil
from concurrent.futures import ThreadPoolExecutor, as_completed
import tarfile
import tempfile
import argparse
# ==============================================================================
# Module: config.py
# ==============================================================================
"""
Bootstrap Source Configuration Module
Central configuration and constants for workspace bootstrap.
Defines tier specifications, default structures, and branding.
"""
# Version Information
VERSION = "1.0.1"
DEFAULT_PYTHON_VERSION = "3.11"
# Exit Codes
EXIT_SUCCESS = 0
EXIT_VALIDATION_ERROR = 1
EXIT_CREATION_ERROR = 2
EXIT_UPGRADE_ERROR = 3
EXIT_ROLLBACK_ERROR = 4
EXIT_CONFIG_ERROR = 5
EXIT_WORKSPACE_ERROR = 6
EXIT_INTERRUPT = 130
EXIT_UNEXPECTED_ERROR = 255
SCRIPT_NAME = "Gemini Workspace Framework"
# Supported LLM Providers
SUPPORTED_PROVIDERS = ["gemini"]
DEFAULT_PROVIDER = "gemini"
# Tier Definitions
TIER_NAMES = {"1": "Lite", "2": "Standard", "3": "Enterprise"}
TIER_DESCRIPTIONS = {
"1": "Lightweight workspace with basic features",
"2": "Full-featured workspace with testing and quality gates",
"3": "Enterprise workspace with advanced features and evaluations",
}
# Directory Structure Templates
BASE_DIRECTORIES = [
"src",
"tests",
"docs",
"logs",
"scratchpad",
".agent/skills",
".agent/workflows",
]
TIER_SPECIFIC_DIRECTORIES = {
"1": [], # Lite has no additional directories
"2": ["docs/architecture", "docs/api"],
"3": ["docs/architecture", "docs/api", "docs/evaluations", "benchmarks"],
}
# Script Organization Patterns
# Maps tier -> category -> list of script names (without .py extension)
SCRIPT_CATEGORIES = {
"1": { # Lite: flat structure in scripts/
"": [
"run_audit",
"manage_session",
"check_status",
"index_docs",
"list_skills",
"manage_skills",
"explore_skills",
]
},
"2": { # Standard: functional categories
"workspace": ["run_audit", "manage_session", "check_status", "create_snapshot"],
"skills": ["list_skills", "manage_skills", "explore_skills"],
"docs": ["index_docs"],
},
"3": { # Enterprise: domain-based (shared is default)
"shared": ["run_audit", "manage_session", "check_status", "create_snapshot"]
},
}
# Standard script verbs for verb_noun.py naming convention
SCRIPT_VERBS = [
"run", # Execute processes (audit, tests)
"check", # Inspections (status, health)
"manage", # CRUD operations (session, config, skills)
"generate", # Create artifacts (reports, docs)
"sync", # Data synchronization
"index", # Build search indices
"list", # Display collections
"create", # Create new items (snapshots)
"explore", # Discovery/exploration (skills)
]
# File Permissions (Standard tier paths as reference)
EXECUTABLE_FILES = [
"scripts/workspace/run_audit.py",
"scripts/workspace/manage_session.py",
"scripts/workspace/check_status.py",
"scripts/workspace/create_snapshot.py",
"scripts/docs/index_docs.py",
"scripts/skills/list_skills.py",
"scripts/skills/manage_skills.py",
"scripts/skills/explore_skills.py",
]
# Snapshot configuration
SNAPSHOTS_DIR = ".snapshots"
# Color Codes for Terminal Output
COLORS = {
"BLUE": "\\033[1;34m",
"GREEN": "\\033[1;32m",
"YELLOW": "\\033[1;33m",
"RED": "\\033[1;31m",
"NC": "\\033[0m", # No Color
}
# Branding
BRANDING = {
"emoji": {
"system": "⚙️",
"tools": "🔧",
"branding": "🎨",
"session": "⏱️",
"health": "🏥",
"hygiene": "🧹",
"security": "🛡️",
"app": "🚀",
"test": "🧪",
"docs": "📚",
"env": "📦",
"archive": "🛡️",
}
}
# Makefile .PHONY targets by tier
PHONY_TARGETS = {
"1": [
"run",
"test",
"install",
"context",
"clean",
"audit",
"session-start",
"session-end",
"init",
"list-skills",
"help",
"doctor",
"status",
"health",
"lint",
"format",
"ci-local",
"deps-check",
"security-scan",
"session-force-end-all",
"onboard",
"sync",
"search",
"list-todos",
"index",
"backup",
"skill-add",
"skill-remove",
],
"2": [
"run",
"test",
"test-watch",
"coverage",
"typecheck",
"install",
"context",
"clean",
"audit",
"session-start",
"session-end",
"init",
"list-skills",
"help",
"snapshot",
"restore",
"doctor",
"status",
"health",
"format",
"update",
"docs",
"lint",
"ci-local",
"deps-check",
"security-scan",
"session-force-end-all",
"onboard",
"backup",
"sync",
"search",
"list-todos",
"index",
"skill-add",
"skill-remove",
],
"3": [
"scan",
"test",
"test-watch",
"coverage",
"typecheck",
"audit",
"eval",
"context",
"context-frontend",
"context-backend",
"install",
"clean",
"session-start",
"session-end",
"init",
"list-skills",
"shift-report",
"snapshot",
"restore",
"doctor",
"status",
"health",
"help",
"lint",
"format",
"update",
"lock",
"docs",
"ci-local",
"deps-check",
"security-scan",
"session-force-end-all",
"onboard",
"backup",
"sync",
"search",
"list-todos",
"index",
"skill-add",
"skill-remove",
],
}
# Default requirements by tier
DEFAULT_REQUIREMENTS = {
"1": [
"# Lite Workspace Dependencies",
"# Add your project dependencies here",
"",
"# Code Quality",
"ruff>=0.1.0",
],
"2": [
"# Standard Workspace Dependencies",
"# Add your project dependencies here",
"",
"# Testing",
"pytest>=7.0.0",
"pytest-cov>=4.0.0",
"",
"# Code Quality",
"ruff>=0.1.0",
"mypy>=1.0.0",
],
"3": [
"# Enterprise Workspace Dependencies",
"# Add your project dependencies here",
"",
"# High-performance package manager (recommended)",
"uv>=0.1.0",
"",
"# Testing & Quality",
"pytest>=7.0.0",
"pytest-cov>=4.0.0",
"pytest-benchmark>=4.0.0",
"",
"# Code Quality",
"ruff>=0.1.0",
"mypy>=1.0.0",
],
}
# Git ignore patterns
GITIGNORE_PATTERNS = [
"# Python",
"__pycache__/",
"*.py[cod]",
"*$py.class",
"*.so",
".Python",
"build/",
"develop-eggs/",
"dist/",
"downloads/",
"eggs/",
".eggs/",
"lib/",
"lib64/",
"parts/",
"sdist/",
"var/",
"wheels/",
"*.egg-info/",
".installed.cfg",
"*.egg",
"",
"# Virtual Environment",
"venv/",
"ENV/",
"env/",
".venv/",
"",
"# IDE",
".vscode/",
".idea/",
"*.swp",
"*.swo",
"*~",
"",
"# Project Specific",
"logs/*.log",
"scratchpad/*",
".env",
".env.local",
"",
"# Testing",
".pytest_cache/",
".coverage",
"htmlcov/",
"",
"# Gemini Cache",
".gemini/cache/",
"",
"# OS",
".DS_Store",
"Thumbs.db",
]
def get_all_directories(tier: str) -> List[str]:
"""Get complete directory list for a tier."""
return BASE_DIRECTORIES + TIER_SPECIFIC_DIRECTORIES.get(tier, [])
def get_tier_name(tier: str) -> str:
"""Get human-readable tier name."""
return TIER_NAMES.get(tier, "Unknown")
def get_phony_targets(tier: str) -> List[str]:
"""Get .PHONY targets for a tier."""
return PHONY_TARGETS.get(tier, PHONY_TARGETS["1"])
def get_gitignore_for_tier(tier: str) -> List[str]:
"""Get complete .gitignore patterns for a tier including data directories.
Args:
tier: Workspace tier ("1" for Lite, "2" for Standard, "3" for Enterprise)
Returns:
Complete list of gitignore patterns
"""
patterns = GITIGNORE_PATTERNS.copy()
# Add tier-specific data patterns
if tier in ["1", "2"]: # Lite/Standard: flat data structure
patterns.extend(
[
"",
"# Data (Lite/Standard tier pattern)",
"data/inputs/*",
"!data/inputs/.gitkeep",
"data/outputs/*",
]
)
else: # Enterprise: domain-based data structure
patterns.extend(
[
"",
"# Data (Enterprise tier pattern)",
"data/*/inputs/*",
"data/*/outputs/*",
"!data/*/.gitkeep",
]
)
return patterns
# Tier Metadata
TIERS = {
"1": {
"name": "Lite",
"desc": "Lightweight workspace with basic features",
"order": 1,
},
"2": {
"name": "Standard",
"desc": "Full-featured workspace with testing",
"order": 2,
},
"3": {
"name": "Enterprise",
"desc": "Enterprise workspace with advanced features",
"order": 3,
},
}
# Templates (placeholder - can be extended)
TEMPLATES = {}
# ==============================================================================
# Module: core_utils.py
# ==============================================================================
"""
Core Bootstrap Module
Defines exceptions, utilities, validators, and helper functions.
"""
# Import constants from config (these are available in the monolithic build)
# Version constant
VERSION = "1.0.1"
DEFAULT_PYTHON_VERSION = "3.11"
VALID_PYTHON_VERSION_PATTERN = re.compile(r"^3\.\d+$")
# Global flag for color output
USE_COLOR: bool = os.environ.get("NO_COLOR") is None
class Colors:
GREEN = "\033[92m"
RED = "\033[91m"
YELLOW = "\033[93m"
BLUE = "\033[94m"
CYAN = "\033[96m"
BOLD = "\033[1m"
DIM = "\033[2m"
RESET = "\033[0m"
def _c(code: str) -> str:
"""Return color code if colors are enabled, empty string otherwise."""
return code if USE_COLOR else ""
def show_progress(step: int, total: int, message: str) -> None:
"""Display progress indicator for long-running operations."""
bar_length = 30
filled = int(bar_length * step / total)
bar = "█" * filled + "░" * (bar_length - filled)
percent = int(100 * step / total)
print(
f"\r{_c(Colors.CYAN)}[{bar}] {percent}% {_c(Colors.RESET)} {message}",
end="",
flush=True,
)
if step == total:
print() # New line when complete
def success(msg: str) -> None:
print(f"{_c(Colors.GREEN)}✅ {msg}{_c(Colors.RESET)}")
def error(msg: str) -> None:
print(f"{_c(Colors.RED)}❌ {msg}{_c(Colors.RESET)}")
def warning(msg: str) -> None:
print(f"{_c(Colors.YELLOW)}⚠️ {msg}{_c(Colors.RESET)}")
def info(msg: str) -> None:
print(f"{_c(Colors.BLUE)}ℹ️ {msg}{_c(Colors.RESET)}")
def header(msg: str) -> None:
print(f"\n{_c(Colors.BOLD)}{msg}{_c(Colors.RESET)}")
def dim(msg: str) -> None:
print(f"{_c(Colors.DIM)}{msg}{_c(Colors.RESET)}")
# --- STRUCTURED LOGGING & TELEMETRY ---
# Configure structured logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def validate_project_name(name: str) -> None:
"""Validate project name.
Args:
name: Project name to validate
Raises:
ValidationError: If project name is invalid
"""
if not name:
raise ValidationError("Project name cannot be empty")
if len(name) > 50:
raise ValidationError("Project name must be 50 characters or less")
if not re.match(r"^[a-zA-Z][a-zA-Z0-9_-]*$", name):
raise ValidationError(
"Project name must start with a letter and contain only letters, numbers, underscores, and hyphens"
)
# Path traversal protection
if ".." in name or "/" in name or "\\" in name:
raise ValidationError(
"Project name cannot contain path separators or parent directory references"
)
reserved = {"test", "tests", "src", "lib", "bin", "build", "dist"}
if name.lower() in reserved:
raise ValidationError(f"'{name}' is a reserved name, please choose another")
def validate_python_version(version: str) -> None:
"""Validate Python version string format.
Args:
version: Expected format like '3.10', '3.11', '3.12'
Raises:
ValidationError: If Python version format is invalid
"""
if not version:
raise ValidationError("Python version cannot be empty")
if not VALID_PYTHON_VERSION_PATTERN.match(version):
raise ValidationError(
f"Invalid Python version '{version}'. Expected format: 3.10, 3.11, 3.12, etc."
)
def validate_tier_upgrade(current_tier: str, target_tier: str) -> None:
"""Validate tier upgrade path prevents downgrades.
Args:
current_tier: Current workspace tier (1, 2, or 3)
target_tier: Target tier for upgrade
Raises:
ValidationError: If upgrade path is invalid
"""
try:
current = int(current_tier)
target = int(target_tier)
if target < current:
raise ValidationError(
f"Cannot downgrade from Tier {current_tier} ({TIERS[current_tier]['name']}) to Tier {target_tier} ({TIERS[target_tier]['name']})"
)
if target == current:
raise ValidationError(
f"Workspace is already at Tier {current_tier} ({TIERS[current_tier]['name']})"
)
# Validate tier exists
if target_tier not in TIERS:
raise ValidationError(
f"Invalid target tier '{target_tier}'. Must be 1, 2, or 3"
)
except (ValueError, KeyError):
raise ValidationError(
f"Invalid tier values: current='{current_tier}', target='{target_tier}'"
)
def validate_template_name(name: str) -> None:
"""Validate template name exists in TEMPLATES.
Args:
name: Template name to validate
Raises:
ValidationError: If template name is unknown
"""
if not name:
raise ValidationError("Template name cannot be empty")
if name not in TEMPLATES:
available = ", ".join(sorted(TEMPLATES.keys()))
raise ValidationError(
f"Unknown template '{name}'. Available templates: {available}"
)
def validate_manifest_path(path: str) -> None:
"""Prevent path traversal in context manifests.
Args:
path: File path from manifest
Raises:
ValidationError: If path contains security vulnerabilities
Security:
Prevents loading files outside workspace via path traversal.
"""
if not path:
raise ValidationError("Manifest path cannot be empty")
# Reject absolute paths
if path.startswith("/") or (
len(path) > 1 and path[1] == ":"
): # Unix or Windows absolute
raise ValidationError(f"Manifest paths must be relative, not absolute: {path}")
# Reject UNC paths (Windows network paths)
if path.startswith("\\\\"):
raise ValidationError(f"UNC paths not allowed in manifest: {path}")
# Reject parent directory references
if ".." in path.split("/"):
raise ValidationError(f"Path traversal detected in manifest: {path}")
# Check for null bytes (security)
if "\0" in path:
raise ValidationError(f"Null byte detected in manifest path: {path}")
def validate_rollback_backup(backup_name: str, workspace_path: Path) -> None:
"""Validate backup exists before attempting rollback.
Args:
backup_name: Name of backup/snapshot to restore
workspace_path: Path to workspace
Raises:
ValidationError: If backup doesn't exist or is invalid
"""
if not backup_name:
raise ValidationError("Backup name cannot be empty")
backup_dir = workspace_path / SNAPSHOTS_DIR / backup_name
if not backup_dir.exists():
# List available backups
snapshots_path = workspace_path / SNAPSHOTS_DIR
if snapshots_path.exists():
available = [d.name for d in snapshots_path.iterdir() if d.is_dir()]
if available:
available_str = ", ".join(sorted(available))
raise ValidationError(
f"Backup '{backup_name}' not found. Available: {available_str}"
)
raise ValidationError(f"Backup '{backup_name}' not found. No backups exist.")
if not backup_dir.is_dir():
raise ValidationError(
f"Backup path exists but is not a directory: {backup_dir}"
)
def load_config(config_path: Path | None = None) -> dict:
"""Load config from .gemini-bootstrap.json if it exists.
Args:
config_path: Optional explicit path; defaults to cwd/.gemini-bootstrap.json
Returns:
Configuration dictionary or empty dict if not found/invalid
Security:
Path traversal validation prevents loading config from outside cwd.
"""
path = config_path or Path.cwd() / ".gemini-bootstrap.json"
# Security: Validate path doesn't traverse outside expected locations
try:
resolved_path = path.resolve()
cwd_resolved = Path.cwd().resolve()
# Allow paths within cwd or explicit absolute paths that exist
if config_path is None and not str(resolved_path).startswith(str(cwd_resolved)):
warning("Config path traversal detected, ignoring")
return {}
except (OSError, ValueError):
warning("Invalid config path, ignoring")
return {}
if path.exists():
try:
with open(path) as f:
return json.load(f)
except json.JSONDecodeError:
warning("Invalid .gemini-bootstrap.json (malformed JSON), ignoring")
except PermissionError:
warning("Cannot read .gemini-bootstrap.json (permission denied), ignoring")
except Exception as e:
warning(f"Unexpected error reading .gemini-bootstrap.json: {e}")
return {}
def _get_file_cache_key(path: Path) -> str:
"""Generate cache key based on file modification time for cache invalidation.
Args:
path: File or directory path to generate cache key for
Returns:
Cache key string combining path and mtime, or path:missing if not exists
Used by @lru_cache decorated functions to automatically invalidate cache
when the underlying file changes.
"""
if not path.exists():
return f"{path}:missing"
try:
if path.is_file():
mtime = path.stat().st_mtime
return f"{path}:{mtime}"
else:
# For directories, hash all file mtimes for comprehensive invalidation
mtimes = []
for file in path.rglob("*"):
if file.is_file():
try:
mtimes.append(
f"{file.relative_to(path)}:{file.stat().st_mtime}"
)
except (OSError, ValueError):
# Skip files we can't stat
continue
if mtimes:
return (
f"{path}:"
+ hashlib.sha256("".join(sorted(mtimes)).encode()).hexdigest()
)
else:
return f"{path}:empty"
except (OSError, PermissionError):
# If we can't access the file, use a timestamp-based key
return f"{path}:error:{datetime.now(timezone.utc).timestamp()}"
# --- CUSTOM EXCEPTION HIERARCHY ---
class WorkspaceError(Exception):
"""Base exception for all workspace-related errors.
All workspace operations should raise subclasses of this exception instead
of using sys.exit(), allowing for proper exception handling and testing.
"""
pass
class ValidationError(WorkspaceError):
"""Raised when validation fails (project name, tier, template, paths, etc.).
Examples:
- Invalid project name format
- Invalid tier upgrade path (downgrade attempt)
- Invalid Python version string
- Path traversal detected in manifest
"""
pass
class CreationError(WorkspaceError):
"""Raised when workspace creation fails.
Examples:
- Directory already exists
- Insufficient permissions
- Disk space issues
- Template application errors
"""
pass
class UpgradeError(WorkspaceError):
"""Raised when workspace upgrade fails.
Examples:
- Invalid upgrade path (downgrade attempt)
- Missing workspace.json
- Backup creation fails
- File conflicts during upgrade
"""
pass
class RollbackError(WorkspaceError):
"""Raised when rollback/restore operation fails.
Examples:
- Backup/snapshot not found
- Restore operation fails
- Invalid backup structure
"""
pass
class ConfigurationError(WorkspaceError):
"""Raised when configuration is invalid or missing.
Examples:
- Malformed workspace.json
- Missing required fields
- Invalid settings - Schema validation failures
"""
pass
# ==============================================================================
# Module: providers/base.py
# ==============================================================================
"""
LLM Provider Base Class
Abstract interface for LLM-specific workspace configurations.
Providers implement templates for config files, MCP settings, and directory structures.
"""
class LLMProvider(ABC):
"""Abstract base class for LLM workspace providers."""
@property
@abstractmethod
def name(self) -> str:
"""Provider name."""
pass
@property
@abstractmethod
def config_filename(self) -> str:
"""Main configuration file name (e.g., 'GEMINI.md')."""
pass
@property
@abstractmethod
def config_dirname(self) -> str:
"""Configuration directory name (e.g., '.gemini')."""
pass
@abstractmethod
def get_config_template(self, tier: str, project_name: str) -> str:
"""
Generate the main configuration file content.
Args:
tier: Workspace tier ("1", "2", or "3")
project_name: Name of the workspace project
Returns:
Configuration file content as string
"""
pass
@abstractmethod
def get_readme_template(self, tier: str, project_name: str) -> str:
"""
Generate README.md content.
Args:
tier: Workspace tier
project_name: Name of the workspace project
Returns:
README content as string
"""
pass
@abstractmethod
def get_mcp_config(self) -> Dict:
"""
Get MCP (Model Context Protocol) server configuration.
Returns:
MCP configuration as dictionary
"""
pass
@abstractmethod
def get_settings(self, tier: str) -> Dict:
"""
Get provider-specific settings.
Args:
tier: Workspace tier
Returns:
Settings dictionary
"""
pass
def get_additional_files(self, tier: str, project_name: str) -> Dict[str, str]:
"""
Get any additional provider-specific files.
Args:
tier: Workspace tier
project_name: Name of the workspace project
Returns:
Dictionary mapping file paths to content
"""
return {}
def get_additional_directories(self, tier: str) -> List[str]:
"""
Get any additional provider-specific directories.
Args:
tier: Workspace tier
Returns:
List of directory paths
"""
return []
# ==============================================================================
# Module: providers/gemini.py
# ==============================================================================
"""
Gemini LLM Provider
Concrete implementation of LLMProvider for Google Gemini workspaces.
"""