-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathskill_split.py
More file actions
executable file
·1496 lines (1253 loc) · 52.8 KB
/
skill_split.py
File metadata and controls
executable file
·1496 lines (1253 loc) · 52.8 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
"""
skill-split - Intelligent Markdown/YAML Section Splitter
A Python tool that decomposes skill/command/reference files into discrete
sections stored in a database, enabling progressive disclosure.
"""
import argparse
import sys
import os
from pathlib import Path
from typing import Optional
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent))
from core.parser import Parser
from core.detector import FormatDetector
from core.database import DatabaseStore
from core.hashing import compute_file_hash, compute_combined_hash
from core.validator import Validator
from core.recomposer import Recomposer
from core.query import QueryAPI
from models import FileFormat, FileType, Section
# Import HandlerFactory for script and component file handling
from handlers.factory import HandlerFactory
# Lazy imports for Supabase-dependent modules
# (to allow running core commands without Supabase installed)
SupabaseStore = None
from core.checkout_manager import CheckoutManager
SecretManager = None
def get_default_db_path():
"""Get database path from env var or use default location."""
env_path = os.getenv("SKILL_SPLIT_DB")
if env_path:
return os.path.expanduser(env_path)
# Check for Claude databases directory
claude_db_dir = Path.home() / ".claude" / "databases"
if claude_db_dir.exists():
return str(claude_db_dir / "skill-split.db")
# Fall back to current directory
return "./skill_split.db"
def _ensure_supabase_imports():
"""Lazy load Supabase dependencies when needed."""
global SupabaseStore, SecretManager
if SupabaseStore is None:
try:
from core.supabase_store import SupabaseStore as SB
from core.secret_manager import SecretManager as SM
SupabaseStore = SB
SecretManager = SM
except ImportError as e:
print(f"Error: Supabase modules not available. {e}", file=sys.stderr)
sys.exit(1)
def _get_supabase_store(use_secret_manager: bool = True, secrets_config: Optional[str] = None):
"""Get SupabaseStore instance from environment credentials or SecretManager.
Args:
use_secret_manager: If True, try SecretManager before environment (default: True)
secrets_config: Optional path to secrets config file
Returns:
SupabaseStore instance if credentials are valid, None otherwise.
"""
_ensure_supabase_imports()
# Try SecretManager first if enabled
if use_secret_manager and SecretManager:
try:
secret_manager = SecretManager(config_path=secrets_config)
return SupabaseStore(secret_manager=secret_manager)
except Exception:
# Fall back to environment variables
pass
# Fall back to environment variables
supabase_url = os.getenv("SUPABASE_URL")
supabase_key = _get_supabase_key()
if not supabase_url or not supabase_key:
print(
"Error: Supabase credentials not found. Tried: SecretManager, environment variables.\n"
"Set SUPABASE_URL and SUPABASE_KEY environment variables, or configure ~/.claude/secrets.json",
file=sys.stderr
)
return None
return SupabaseStore(supabase_url, supabase_key)
def _get_supabase_key(use_secret_manager: bool = True, secrets_config: Optional[str] = None) -> Optional[str]:
"""Return Supabase key from SecretManager or supported environment variables.
Args:
use_secret_manager: If True, try SecretManager first
secrets_config: Optional path to secrets config file
Returns:
Supabase key or None if not found
"""
_ensure_supabase_imports()
# Try SecretManager first if enabled
if use_secret_manager and SecretManager:
try:
secret_manager = SecretManager(config_path=secrets_config)
# Try various key names
try:
return secret_manager.get_secret("SUPABASE_KEY")
except Exception:
try:
return secret_manager.get_secret("supabase_key")
except Exception:
pass # Fall through to environment
except Exception:
pass # Fall through to environment
# Fall back to environment variables
return (
os.getenv("SUPABASE_KEY")
or os.getenv("SUPABASE_PUBLISHABLE_KEY")
or os.getenv("SUPABASE_SECRET_KEY")
)
def cmd_parse(args) -> int:
"""Parse a file and display its structure."""
file_path = args.file
if not Path(file_path).exists():
print(f"Error: File not found: {file_path}", file=sys.stderr)
return 1
with open(file_path) as f:
content = f.read()
# Try to use HandlerFactory for script and component files
handler = None
try:
if HandlerFactory.is_supported(file_path):
handler = HandlerFactory.create_handler(file_path)
except (ValueError, FileNotFoundError):
# File not supported or doesn't exist, fall back to parser
pass
if handler:
# Use handler for script/component files
doc = handler.parse()
file_type = handler.get_file_type()
file_format = handler.get_file_format()
else:
# Fall back to existing Parser for markdown files
detector = FormatDetector()
file_type, file_format = detector.detect(file_path, content)
parser = Parser()
doc = parser.parse(file_path, content, file_type, file_format)
# Display results
print(f"File: {file_path}")
print(f"Type: {file_type.value}")
print(f"Format: {file_format.value}")
print()
if doc.frontmatter:
print("Frontmatter:")
print("---")
print(doc.frontmatter)
print("---")
print()
print("Sections:")
_print_sections(doc.sections, indent=0)
return 0
def _print_sections(sections, indent: int) -> None:
"""Print sections with indentation."""
for section in sections:
prefix = " " * indent
level_indicator = "#" * section.level
print(f"{prefix}{level_indicator} {section.title}")
print(f"{prefix} Lines: {section.line_start}-{section.line_end}")
if section.children:
_print_sections(section.children, indent + 1)
def cmd_validate(args) -> int:
"""Validate a file's structure."""
file_path = args.file
if not Path(file_path).exists():
print(f"Error: File not found: {file_path}", file=sys.stderr)
return 1
with open(file_path) as f:
content = f.read()
# Try to use HandlerFactory for script and component files
handler = None
try:
if HandlerFactory.is_supported(file_path):
handler = HandlerFactory.create_handler(file_path)
except (ValueError, FileNotFoundError):
# File not supported or doesn't exist, fall back to parser
pass
if handler:
# Use handler for script/component files
doc = handler.parse()
file_type = handler.get_file_type()
file_format = handler.get_file_format()
result = handler.validate()
errors = result.errors
warnings = result.warnings
else:
# Fall back to existing Parser for markdown files
detector = FormatDetector()
file_type, file_format = detector.detect(file_path, content)
parser = Parser()
doc = parser.parse(file_path, content, file_type, file_format)
# Basic validation
errors = []
warnings = []
if not doc.sections:
errors.append("No sections found in file")
# Check for empty sections
def check_empty(sections, path=""):
for section in sections:
full_path = f"{path}/{section.title}" if path else section.title
if not section.content.strip() and not section.children:
warnings.append(f"Empty section: {full_path}")
check_empty(section.children, full_path)
check_empty(doc.sections)
# Report
print(f"Validating: {file_path}")
print(f"Type: {file_type.value}, Format: {file_format.value}")
print()
if errors:
print("Errors:")
for error in errors:
print(f" ✗ {error}")
if warnings:
print("Warnings:")
for warning in warnings:
print(f" ⚠ {warning}")
if not errors and not warnings:
print("✓ No issues found")
return 1 if errors else 0
def cmd_store(args) -> int:
"""Store a parsed file in the database."""
file_path = args.file
db_path = args.db or get_default_db_path()
if not Path(file_path).exists():
print(f"Error: File not found: {file_path}", file=sys.stderr)
return 1
with open(file_path) as f:
content = f.read()
# Try to use HandlerFactory for script and component files
handler = None
try:
if HandlerFactory.is_supported(file_path):
handler = HandlerFactory.create_handler(file_path)
except (ValueError, FileNotFoundError):
# File not supported or doesn't exist, fall back to parser
pass
if handler:
# Use handler for script/component files
doc = handler.parse()
file_type = handler.get_file_type()
file_format = handler.get_file_format()
else:
# Fall back to existing Parser for markdown files
detector = FormatDetector()
file_type, file_format = detector.detect(file_path, content)
parser = Parser()
doc = parser.parse(file_path, content, file_type, file_format)
# Compute hash (combined for multi-file components)
related_paths = []
if handler and hasattr(handler, "get_related_files"):
related_paths = handler.get_related_files()
if related_paths:
content_hash = compute_combined_hash(file_path, related_paths)
else:
content_hash = compute_file_hash(file_path)
if not content_hash:
print(f"Error: Unable to compute hash for {file_path}", file=sys.stderr)
return 1
# Store in database
store = DatabaseStore(db_path)
try:
file_id = store.store_file(file_path, doc, content_hash)
except Exception as e:
print(f"Error storing file: {e}", file=sys.stderr)
return 1
# Display results
print(f"File: {file_path}")
print(f"File ID: {file_id}")
print(f"Hash: {content_hash}")
print(f"Type: {file_type.value}")
print(f"Format: {file_format.value}")
print(f"Sections: {_count_sections(doc.sections)}")
return 0
def cmd_get(args) -> int:
"""Retrieve a file from the database and display metadata."""
file_path = args.file
db_path = args.db or get_default_db_path()
store = DatabaseStore(db_path)
result = store.get_file(file_path)
if result is None:
print(f"Error: File not found in database: {file_path}", file=sys.stderr)
return 1
metadata, sections = result
# Display results
print(f"File: {metadata.path}")
print(f"Type: {metadata.type.value}")
print(f"Hash: {metadata.hash}")
if metadata.frontmatter:
print("Frontmatter:")
print("---")
print(metadata.frontmatter)
print("---")
print(f"Sections: {_count_sections(sections)}")
return 0
def cmd_tree(args) -> int:
"""Show section hierarchy for a file in the database."""
file_path = args.file
db_path = args.db or get_default_db_path()
store = DatabaseStore(db_path)
sections = store.get_section_tree(file_path)
if not sections:
# File might not exist or have no sections
result = store.get_file(file_path)
if result is None:
print(f"Error: File not found in database: {file_path}", file=sys.stderr)
return 1
print(f"File: {file_path}")
print("(No sections)")
return 0
id_map = _build_section_id_map(db_path, file_path)
print(f"File: {file_path}")
print()
print("Sections:")
_print_sections_with_ids(sections, indent=0, id_map=id_map)
return 0
def cmd_verify(args) -> int:
"""Verify a file by storing it and validating round-trip integrity."""
file_path = args.file
db_path = args.db or get_default_db_path()
if not Path(file_path).exists():
print(f"Error: File not found: {file_path}", file=sys.stderr)
return 1
with open(file_path) as f:
content = f.read()
# Try to use HandlerFactory for script and component files
handler = None
try:
if HandlerFactory.is_supported(file_path):
handler = HandlerFactory.create_handler(file_path)
except (ValueError, FileNotFoundError):
# File not supported or doesn't exist, fall back to parser
pass
if handler:
# Use handler for script/component files
doc = handler.parse()
file_type = handler.get_file_type()
file_format = handler.get_file_format()
else:
# Fall back to existing Parser for markdown files
detector = FormatDetector()
file_type, file_format = detector.detect(file_path, content)
parser = Parser()
doc = parser.parse(file_path, content, file_type, file_format)
# Compute hash (combined for multi-file components)
related_paths = []
if handler and hasattr(handler, "get_related_files"):
related_paths = handler.get_related_files()
if related_paths:
content_hash = compute_combined_hash(file_path, related_paths)
else:
content_hash = compute_file_hash(file_path)
if not content_hash:
print(f"Error: Unable to compute hash for {file_path}", file=sys.stderr)
return 1
# Store in database (or update if exists)
store = DatabaseStore(db_path)
try:
file_id = store.store_file(file_path, doc, content_hash)
except Exception as e:
print(f"Error storing file: {e}", file=sys.stderr)
return 1
# Run round-trip validation
recomposer = Recomposer(store)
validator = Validator(store, recomposer)
result = validator.validate_round_trip(file_path)
# Display results
print(f"File: {file_path}")
print(f"File ID: {file_id}")
print(f"Type: {file_type.value}")
print(f"Format: {file_format.value}")
print()
# Show validity status
if result.is_valid:
print("Valid")
else:
print("Invalid")
print()
# Show hashes
print(f"original_hash: {result.original_hash}")
print(f"recomposed_hash: {result.recomposed_hash}")
print()
# Show errors
if result.errors:
print("Errors:")
for error in result.errors:
print(f" {error}")
print()
# Show warnings
if result.warnings:
print("Warnings:")
for warning in result.warnings:
print(f" {warning}")
# Return 0 if valid, 1 if invalid
return 0 if result.is_valid else 1
def _count_sections(sections) -> int:
"""Count all sections recursively."""
count = len(sections)
for section in sections:
count += _count_sections(section.children)
return count
def cmd_ingest(args) -> int:
"""Parse files from directory and store in Supabase."""
_ensure_supabase_imports()
source_dir = args.source_dir
if not Path(source_dir).exists():
print(f"Error: Directory not found: {source_dir}", file=sys.stderr)
return 1
# Initialize store
use_sm = not getattr(args, 'no_use_secret_manager', False) # Inverted flag
secrets_cfg = getattr(args, 'secrets_config', None)
store = _get_supabase_store(use_secret_manager=use_sm, secrets_config=secrets_cfg)
if store is None:
return 1
# Find all supported files in source directory
source_path = Path(source_dir)
files = []
files.extend(source_path.glob("*.md"))
files.extend(source_path.glob("**/*.md"))
# Include handler-supported extensions (json + scripts)
for ext in HandlerFactory.list_supported_extensions():
files.extend(source_path.glob(f"*{ext}"))
files.extend(source_path.glob(f"**/*{ext}"))
# De-duplicate
files = list({str(p): p for p in files}.values())
if not files:
print(f"No supported files found in {source_dir}")
return 0
# Parse and store each file
detector = FormatDetector()
parser = Parser()
ingested_count = 0
for file_path in files:
try:
with open(file_path) as f:
content = f.read()
# Try handler first for supported component/script files
handler = None
try:
if HandlerFactory.is_supported(str(file_path)):
handler = HandlerFactory.create_handler(str(file_path))
except (ValueError, FileNotFoundError):
handler = None
if handler:
doc = handler.parse()
else:
# Detect format and type
file_type, file_format = detector.detect(str(file_path), content)
# Parse
doc = parser.parse(str(file_path), content, file_type, file_format)
# Compute hash
related_paths = []
if handler and hasattr(handler, "get_related_files"):
related_paths = handler.get_related_files()
if related_paths:
content_hash = compute_combined_hash(str(file_path), related_paths)
else:
content_hash = compute_file_hash(str(file_path))
if not content_hash:
print(f"Warning: Could not compute hash for {file_path}", file=sys.stderr)
continue
# Store in Supabase
file_id = store.store_file(
storage_path=str(file_path),
name=file_path.stem,
doc=doc,
content_hash=content_hash
)
print(f"Stored: {file_path.name} (ID: {file_id})")
ingested_count += 1
except Exception as e:
print(f"Error processing {file_path}: {e}", file=sys.stderr)
continue
print(f"\nIngested {ingested_count} files successfully")
return 0
def cmd_checkout(args) -> int:
"""Checkout file to target path."""
file_id = args.file_id
target_path = args.target_path
user = args.user
db_path = getattr(args, 'db', None)
preserve_headings = not getattr(args, 'strip_headings', False)
if db_path:
store = DatabaseStore(db_path)
try:
file_id_int = int(file_id)
except ValueError:
print(f"Error: Local file_id must be an integer, got: {file_id}", file=sys.stderr)
return 1
manager = CheckoutManager(store)
try:
deployed_path = manager.checkout_file(
file_id=file_id_int,
user=user,
target_path=target_path,
preserve_headings=preserve_headings,
)
print(f"File checked out to: {deployed_path}")
return 0
except Exception as e:
print(f"Error checking out file: {e}", file=sys.stderr)
return 1
_ensure_supabase_imports()
supabase_url = os.getenv("SUPABASE_URL")
supabase_key = _get_supabase_key()
if not supabase_url or not supabase_key:
print("Error: SUPABASE_URL and SUPABASE_KEY required (or use --db for local mode)", file=sys.stderr)
return 1
store = SupabaseStore(supabase_url, supabase_key)
manager = CheckoutManager(store)
try:
deployed_path = manager.checkout_file(
file_id=file_id,
user=user,
target_path=target_path,
preserve_headings=preserve_headings,
)
print(f"File checked out to: {deployed_path}")
return 0
except Exception as e:
print(f"Error checking out file: {e}", file=sys.stderr)
return 1
def cmd_checkin(args) -> int:
"""Checkin file from target path."""
target_path = args.target_path
db_path = getattr(args, 'db', None)
if db_path:
store = DatabaseStore(db_path)
manager = CheckoutManager(store)
try:
manager.checkin(target_path)
print(f"File checked in from: {target_path}")
return 0
except Exception as e:
print(f"Error checking in file: {e}", file=sys.stderr)
return 1
_ensure_supabase_imports()
supabase_url = os.getenv("SUPABASE_URL")
supabase_key = os.getenv("SUPABASE_KEY")
if not supabase_url or not supabase_key:
print("Error: SUPABASE_URL and SUPABASE_KEY required (or use --db for local mode)", file=sys.stderr)
return 1
store = SupabaseStore(supabase_url, supabase_key)
manager = CheckoutManager(store)
try:
manager.checkin(target_path)
print(f"File checked in from: {target_path}")
return 0
except Exception as e:
print(f"Error checking in file: {e}", file=sys.stderr)
return 1
def cmd_list_library(args) -> int:
"""List files in library."""
db_path = getattr(args, 'db', None)
if db_path:
store = DatabaseStore(db_path)
try:
files = store.get_all_files()
if not files:
print("No files in library")
return 0
print(f"{'ID':<6} {'Name':<30} {'Type':<15} {'Path'}")
print("-" * 105)
for f in files:
name = f.get('name', '') or ''
if isinstance(name, list):
name = name[0] if name else ''
print(f"{f['id']:<6} {str(name):<30} {f.get('type',''):<15} {f.get('path','')}")
return 0
except Exception as e:
print(f"Error listing files: {e}", file=sys.stderr)
return 1
_ensure_supabase_imports()
use_sm = not getattr(args, 'no_use_secret_manager', False)
secrets_cfg = getattr(args, 'secrets_config', None)
store = _get_supabase_store(use_secret_manager=use_sm, secrets_config=secrets_cfg)
if store is None:
return 1
try:
files = store.get_all_files()
if not files:
print("No files in library")
return 0
print(f"{'Name':<30} {'Type':<15} {'Storage Path':<50} {'Checkout Status':<20}")
print("-" * 115)
for file_data in files:
name = file_data.get("name", "")
file_type = file_data.get("type", "unknown")
storage_path = file_data.get("storage_path", "")
active_checkouts = store.get_active_checkouts()
checkout_status = "checked out" if any(
c.get("file_id") == file_data.get("id") for c in active_checkouts
) else "available"
print(f"{name:<30} {file_type:<15} {storage_path:<50} {checkout_status:<20}")
return 0
except Exception as e:
print(f"Error listing files: {e}", file=sys.stderr)
return 1
def cmd_status(args) -> int:
"""Show active checkouts."""
db_path = getattr(args, 'db', None)
user = getattr(args, 'user', None)
if db_path:
store = DatabaseStore(db_path)
try:
checkouts = store.get_active_checkouts(user=user)
if not checkouts:
print("No active checkouts" + (f" for user: {user}" if user else ""))
return 0
print(f"{'ID':<6} {'File':<40} {'Target':<50} {'User':<15} {'Checked Out'}")
print("-" * 135)
for c in checkouts:
print(f"{c['id']:<6} {c.get('file_path',''):<40} {c['target_path']:<50} {c['user']:<15} {c.get('checked_out_at','')}")
return 0
except Exception as e:
print(f"Error getting checkout status: {e}", file=sys.stderr)
return 1
_ensure_supabase_imports()
use_sm = not getattr(args, 'no_use_secret_manager', False)
secrets_cfg = getattr(args, 'secrets_config', None)
store = _get_supabase_store(use_secret_manager=use_sm, secrets_config=secrets_cfg)
if store is None:
return 1
try:
checkouts = store.get_active_checkouts(user=user)
if not checkouts:
print("No active checkouts" + (f" for user: {user}" if user else ""))
return 0
print(f"{'File':<40} {'Target Path':<50} {'User':<15} {'Checked Out'}")
print("-" * 130)
for c in checkouts:
file_path = c.get("storage_path", c.get("file_id", ""))
user_val = c.get('user_name') or c.get('user', '')
print(f"{file_path:<40} {c.get('target_path',''):<50} {user_val:<15} {c.get('checked_out_at','')}")
return 0
except Exception as e:
print(f"Error getting checkout status: {e}", file=sys.stderr)
return 1
def cmd_search_library(args) -> int:
"""Search files by query."""
_ensure_supabase_imports()
query = args.query
# Initialize store
use_sm = not getattr(args, 'no_use_secret_manager', False) # Inverted flag
secrets_cfg = getattr(args, 'secrets_config', None)
store = _get_supabase_store(use_secret_manager=use_sm, secrets_config=secrets_cfg)
if store is None:
return 1
try:
results = store.search_files(query)
if not results:
print(f"No files found matching: {query}")
return 0
# Print header
print(f"Found {len(results)} file(s) matching '{query}':")
print()
print(f"{'Name':<30} {'Type':<15} {'Storage Path':<50}")
print("-" * 95)
# Print each result
for file_data in results:
name = file_data.get("name", "")
file_type = file_data.get("type", "unknown")
storage_path = file_data.get("storage_path", "")
print(f"{name:<30} {file_type:<15} {storage_path:<50}")
return 0
except Exception as e:
print(f"Error searching files: {e}", file=sys.stderr)
return 1
def cmd_get_section(args) -> int:
"""Retrieve and display a single section by ID."""
file_path = None
section_id = None
if args.section_id is None:
try:
section_id = int(args.section_id_or_file)
except ValueError:
print("Error: Section ID must be an integer", file=sys.stderr)
sys.exit(1)
else:
file_path = args.section_id_or_file
section_id = args.section_id
db_path = args.db or get_default_db_path()
try:
query_api = QueryAPI(db_path)
section = query_api.get_section(section_id)
if section is None:
print(f"Error: Section {section_id} not found", file=sys.stderr)
sys.exit(1)
# Validate section belongs to file if file_path provided
if file_path:
import sqlite3
with sqlite3.connect(db_path) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.execute(
"""
SELECT f.path
FROM sections s
JOIN files f ON s.file_id = f.id
WHERE s.id = ?
""",
(section_id,),
)
row = cursor.fetchone()
if not row or row["path"] != file_path:
print(f"Error: Section {section_id} does not belong to {file_path}", file=sys.stderr)
sys.exit(1)
# Display section
print(f"Section {section_id}: {section.title}")
print(f"Level: {section.level}")
print(f"Lines: {section.line_start}-{section.line_end}")
print()
print(section.content)
return 0
except Exception as e:
print(f"Error retrieving section: {e}", file=sys.stderr)
sys.exit(1)
def cmd_next(args) -> int:
"""Retrieve and display the next section after given ID."""
file_path = args.file
section_id = args.section_id
first_child = getattr(args, 'child', False)
db_path = args.db or get_default_db_path()
try:
query_api = QueryAPI(db_path)
section = query_api.get_next_section(section_id, file_path, first_child=first_child)
if section is None:
if first_child:
print(f"No child subsection found after section {section_id}")
else:
print(f"No next section found after section {section_id}")
return 0
# Display section
print(f"--- Section {section.title} (Level {section.level}) ---")
print()
print(section.content)
print()
return 0
except Exception as e:
print(f"Error getting next section: {e}", file=sys.stderr)
return 1
def cmd_list_sections(args) -> int:
"""List all sections in a file with IDs and titles."""
file_path = args.file
db_path = args.db or get_default_db_path()
try:
query_api = QueryAPI(db_path)
sections = query_api.get_section_tree(file_path)
if not sections:
print(f"No sections found for file: {file_path}")
return 0
id_map = _build_section_id_map(db_path, file_path)
# Display sections in tree format
print(f"File: {file_path}")
print()
_print_sections_with_ids(sections, indent=0, id_map=id_map)
return 0
except Exception as e:
print(f"Error listing sections: {e}", file=sys.stderr)
sys.exit(1)
def _build_section_id_map(db_path: str, file_path: str) -> dict:
"""Build a mapping from section identity to ID for a specific file."""
import sqlite3
id_map = {}
with sqlite3.connect(db_path) as conn:
conn.row_factory = sqlite3.Row
cursor = conn.execute(
"""
SELECT s.id, s.title, s.level, s.line_start, s.line_end
FROM sections s
JOIN files f ON s.file_id = f.id
WHERE f.path = ?
""",
(file_path,),
)
for row in cursor.fetchall():
key = (row["title"], row["level"], row["line_start"], row["line_end"])
id_map[key] = row["id"]
return id_map
def _print_sections_with_ids(sections, indent: int, id_map: dict) -> None:
"""Print sections with IDs in tree format."""
for section in sections:
prefix = " " * indent
level_indicator = "#" * section.level
key = (section.title, section.level, section.line_start, section.line_end)
section_id = id_map.get(key, "?")
print(f"{prefix}{level_indicator} [{section_id}] {section.title}")
if section.children:
_print_sections_with_ids(section.children, indent + 1, id_map)
def cmd_compose(args) -> int:
"""Compose new skill from section IDs."""
_ensure_supabase_imports()
section_ids_str = args.sections
output_path = args.output
title = args.title or ""
description = args.description or ""
upload = args.upload
validate_flag = getattr(args, 'validate', True) # Default to True
enrich_flag = getattr(args, 'enrich', True) # Default to True
db_path = args.db or get_default_db_path()
# Parse section IDs
try:
section_ids = [int(sid.strip()) for sid in section_ids_str.split(',')]
except ValueError:
print(
"Error [compose.invalid_section_ids] at skill_split.py:cmd_compose: "
"--sections must be comma-separated integers (example: --sections 1,2,3).",
file=sys.stderr,
)
return 1
if not section_ids:
print(
"Error [compose.empty_section_ids] at skill_split.py:cmd_compose: "
"at least one section ID is required. Next step: pass --sections with one or more IDs.",
file=sys.stderr,
)
return 1
try:
from core.skill_composer import SkillComposer
# Create composer
composer = SkillComposer(db_path)
# Compose skill with validation and enrichment flags
composed = composer.compose_from_sections(
section_ids=section_ids,
output_path=output_path,
title=title,
description=description,
validate=validate_flag,
enrich=enrich_flag