-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathcontext.go
More file actions
738 lines (632 loc) · 24.6 KB
/
context.go
File metadata and controls
738 lines (632 loc) · 24.6 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
package codingcontext
import (
"bufio"
"context"
"crypto/sha256"
"fmt"
"log/slog"
"maps"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/hashicorp/go-getter/v2"
"github.com/kitproj/coding-context-cli/pkg/codingcontext/markdown"
"github.com/kitproj/coding-context-cli/pkg/codingcontext/selectors"
"github.com/kitproj/coding-context-cli/pkg/codingcontext/skills"
"github.com/kitproj/coding-context-cli/pkg/codingcontext/taskparser"
"github.com/kitproj/coding-context-cli/pkg/codingcontext/tokencount"
)
// Context holds the configuration and state for assembling coding context
type Context struct {
params taskparser.Params
includes selectors.Selectors
manifestURL string
searchPaths []string
downloadedPaths []string
task markdown.Markdown[markdown.TaskFrontMatter] // Parsed task
rules []markdown.Markdown[markdown.RuleFrontMatter] // Collected rule files
skills skills.AvailableSkills // Discovered skills (metadata only)
totalTokens int
logger *slog.Logger
cmdRunner func(cmd *exec.Cmd) error
resume bool
doBootstrap bool // Controls whether to discover rules, skills, and run bootstrap scripts
agent Agent
userPrompt string // User-provided prompt to append to task
}
// New creates a new Context with the given options
func New(opts ...Option) *Context {
c := &Context{
params: make(taskparser.Params),
includes: make(selectors.Selectors),
rules: make([]markdown.Markdown[markdown.RuleFrontMatter], 0),
skills: skills.AvailableSkills{Skills: make([]skills.Skill, 0)},
logger: slog.New(slog.NewTextHandler(os.Stderr, nil)),
doBootstrap: true, // Default to true for backward compatibility
cmdRunner: func(cmd *exec.Cmd) error {
return cmd.Run()
},
}
for _, opt := range opts {
opt(c)
}
return c
}
// generateIDFromPath generates an ID from a file path by extracting the filename without extension.
// Used to auto-set ID fields in frontmatter when not explicitly provided.
func generateIDFromPath(path string) string {
baseName := filepath.Base(path)
ext := filepath.Ext(baseName)
return strings.TrimSuffix(baseName, ext)
}
type markdownVisitor func(path string, fm *markdown.BaseFrontMatter) error
// findMarkdownFile searches for a markdown file by name in the given directories.
// Returns the path to the file if found, or an error if not found or multiple files match.
func (cc *Context) visitMarkdownFiles(searchDirFn func(path string) []string, visitor markdownVisitor) error {
var searchDirs []string
for _, path := range cc.downloadedPaths {
searchDirs = append(searchDirs, searchDirFn(path)...)
}
for _, dir := range searchDirs {
if _, err := os.Stat(dir); os.IsNotExist(err) {
continue
} else if err != nil {
return fmt.Errorf("failed to stat directory %s: %w", dir, err)
}
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return fmt.Errorf("failed to walk path %s: %w", path, err)
}
ext := filepath.Ext(path) // .md or .mdc
if info.IsDir() || ext != ".md" && ext != ".mdc" {
return nil
}
// If selectors are provided, check if the file matches
// Parse frontmatter to check selectors
var fm markdown.BaseFrontMatter
if _, err := markdown.ParseMarkdownFile(path, &fm); err != nil {
// Skip files that can't be parsed
return nil
}
// Skip files that don't match selectors
matches, reason := cc.includes.MatchesIncludes(fm)
if !matches {
// Log why this file was skipped
if reason != "" {
cc.logger.Info("Skipping file", "path", path, "reason", reason)
}
return nil
}
return visitor(path, &fm)
})
if err != nil {
return fmt.Errorf("failed to walk directory %s: %w", dir, err)
}
}
return nil
}
// findTask searches for a task markdown file and returns it with parameters substituted
func (cc *Context) findTask(taskName string) error {
// Add task name to includes so rules can be filtered
cc.includes.SetValue("task_name", taskName)
taskFound := false
err := cc.visitMarkdownFiles(taskSearchPaths, func(path string, _ *markdown.BaseFrontMatter) error {
baseName := filepath.Base(path)
ext := filepath.Ext(baseName)
if strings.TrimSuffix(baseName, ext) != taskName {
return nil
}
taskFound = true
var frontMatter markdown.TaskFrontMatter
md, err := markdown.ParseMarkdownFile(path, &frontMatter)
if err != nil {
return fmt.Errorf("failed to parse task file %s: %w", path, err)
}
// Automatically set ID to filename (without extension) if not set in frontmatter
if frontMatter.ID == "" {
frontMatter.ID = generateIDFromPath(path)
}
// Extract selector labels from task frontmatter and add them to cc.includes.
// This combines CLI selectors (from -s flag) with task selectors using OR logic:
// rules match if their frontmatter value matches ANY selector value for a given key.
// For example: if CLI has env=development and task has env=production,
// rules with either env=development OR env=production will be included.
cc.mergeSelectors(frontMatter.Selectors)
// Task frontmatter agent field overrides -a flag
if frontMatter.Agent != "" {
agent, err := ParseAgent(frontMatter.Agent)
if err != nil {
return fmt.Errorf("failed to parse agent from task frontmatter: %w", err)
}
cc.agent = agent
}
// Append user_prompt to task content before parsing
// This allows user_prompt to be processed uniformly with task content
taskContent := md.Content
if cc.userPrompt != "" {
// Add delimiter to separate task from user_prompt
if !strings.HasSuffix(taskContent, "\n") {
taskContent += "\n"
}
taskContent += "---\n" + cc.userPrompt
cc.logger.Info("Appended user_prompt to task", "user_prompt_length", len(cc.userPrompt))
}
// Parse the task content (including user_prompt) to separate text blocks from slash commands
task, err := taskparser.ParseTask(taskContent)
if err != nil {
return fmt.Errorf("failed to parse task content in file %s: %w", path, err)
}
// Build the final content by processing each block
// Text blocks are expanded if expand is not false
// Slash command arguments are NOT expanded here - they are passed as literals
// to command files where they may be substituted via ${param} templates
finalContent := strings.Builder{}
for _, block := range task {
if block.Text != nil {
textContent := block.Text.Content()
// Expand parameters in text blocks only if expand is not explicitly set to false
if shouldExpandParams(frontMatter.ExpandParams) {
textContent, err = cc.expandParams(textContent, nil)
if err != nil {
return fmt.Errorf("failed to expand parameters in task file %s: %w", path, err)
}
}
finalContent.WriteString(textContent)
} else if block.SlashCommand != nil {
commandContent, err := cc.findCommand(block.SlashCommand.Name, block.SlashCommand.Params())
if err != nil {
return fmt.Errorf("failed to find command %s: %w", block.SlashCommand.Name, err)
}
finalContent.WriteString(commandContent)
}
}
cc.task = markdown.Markdown[markdown.TaskFrontMatter]{
FrontMatter: frontMatter,
Content: finalContent.String(),
Tokens: tokencount.EstimateTokens(finalContent.String()),
}
cc.totalTokens += cc.task.Tokens
cc.logger.Info("Including task", "name", taskName, "reason", fmt.Sprintf("task name matches '%s'", taskName), "tokens", cc.task.Tokens)
return nil
})
if err != nil {
return fmt.Errorf("failed to find task: %w", err)
}
if !taskFound {
return fmt.Errorf("task not found: %s", taskName)
}
return nil
}
// findCommand searches for a command markdown file and returns its content.
// Commands now support optional frontmatter with the expand field and selectors.
// Parameters are substituted by default (when expand is nil or true).
// Substitution is skipped only when expand is explicitly set to false.
// If the command has selectors in its frontmatter, they are merged into cc.includes
// to allow commands to specify which rules they need.
func (cc *Context) findCommand(commandName string, params taskparser.Params) (string, error) {
var content *string
err := cc.visitMarkdownFiles(commandSearchPaths, func(path string, _ *markdown.BaseFrontMatter) error {
baseName := filepath.Base(path)
ext := filepath.Ext(baseName)
if strings.TrimSuffix(baseName, ext) != commandName {
return nil
}
var frontMatter markdown.CommandFrontMatter
md, err := markdown.ParseMarkdownFile(path, &frontMatter)
if err != nil {
return fmt.Errorf("failed to parse command file %s: %w", path, err)
}
// Automatically set ID to filename (without extension) if not set in frontmatter
if frontMatter.ID == "" {
frontMatter.ID = generateIDFromPath(path)
}
// Extract selector labels from command frontmatter and add them to cc.includes.
// This combines CLI selectors, task selectors, and command selectors using OR logic:
// rules match if their frontmatter value matches ANY selector value for a given key.
cc.mergeSelectors(frontMatter.Selectors)
// Expand parameters only if expand is not explicitly set to false
var processedContent string
if shouldExpandParams(frontMatter.ExpandParams) {
processedContent, err = cc.expandParams(md.Content, params)
if err != nil {
return fmt.Errorf("failed to expand parameters in command file %s: %w", path, err)
}
} else {
processedContent = md.Content
}
content = &processedContent
cc.logger.Info("Including command", "name", commandName, "reason", fmt.Sprintf("referenced by slash command '/%s'", commandName), "path", path)
return nil
})
if err != nil {
return "", err
}
if content == nil {
return "", fmt.Errorf("command not found: %s", commandName)
}
return *content, nil
}
// mergeSelectors adds selectors from a map into cc.includes.
// This is used to combine selectors from task and command frontmatter with CLI selectors.
// The merge uses OR logic: rules match if their frontmatter value matches ANY selector value for a given key.
func (cc *Context) mergeSelectors(selectors map[string]any) {
for key, value := range selectors {
switch v := value.(type) {
case []any:
for _, item := range v {
cc.includes.SetValue(key, fmt.Sprint(item))
}
default:
cc.includes.SetValue(key, fmt.Sprint(v))
}
}
}
// expandParams performs all types of content expansion:
// - Parameter expansion: ${param_name}
// - Command expansion: !`command`
// - Path expansion: @path
// If params is provided, it is merged with cc.params (with params taking precedence).
func (cc *Context) expandParams(content string, params taskparser.Params) (string, error) {
// Merge params with cc.params
mergedParams := make(taskparser.Params)
maps.Copy(mergedParams, cc.params)
maps.Copy(mergedParams, params)
// Use the expand function to handle all expansion types
return mergedParams.Expand(content)
}
// shouldExpandParams returns true if parameter expansion should occur based on the expandParams field.
// If expandParams is nil (not specified), it defaults to true.
func shouldExpandParams(expandParams *bool) bool {
if expandParams == nil {
return true
}
return *expandParams
}
// Run executes the context assembly for the given taskName and returns the assembled result.
// The taskName is looked up in task search paths and its content is parsed into blocks.
// If the taskName cannot be found as a task file, an error is returned.
func (cc *Context) Run(ctx context.Context, taskName string) (*Result, error) {
// Parse manifest file first to get additional search paths
manifestPaths, err := cc.parseManifestFile(ctx)
if err != nil {
return nil, fmt.Errorf("failed to parse manifest file: %w", err)
}
cc.searchPaths = append(cc.searchPaths, manifestPaths...)
// Download all remote directories (including those from manifest)
if err := cc.downloadRemoteDirectories(ctx); err != nil {
return nil, fmt.Errorf("failed to download remote directories: %w", err)
}
defer cc.cleanupDownloadedDirectories()
// If resume mode is enabled, add resume=true as a selector
if cc.resume {
cc.includes.SetValue("resume", "true")
}
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get user home directory: %w", err)
}
// Get the task by name
if err := cc.findTask(taskName); err != nil {
return nil, fmt.Errorf("task not found: %w", err)
}
// Log parameters and selectors after task is found
// This ensures we capture any additions from task/command frontmatter
cc.logger.Info("Parameters", "params", cc.params.String())
cc.logger.Info("Selectors", "selectors", cc.includes.String())
if err := cc.findExecuteRuleFiles(ctx, homeDir); err != nil {
return nil, fmt.Errorf("failed to find and execute rule files: %w", err)
}
// Discover skills (load metadata only for progressive disclosure)
if err := cc.discoverSkills(); err != nil {
return nil, fmt.Errorf("failed to discover skills: %w", err)
}
// Estimate tokens for task
cc.logger.Info("Total estimated tokens", "tokens", cc.totalTokens)
// Build the combined prompt from all rules and task content
var promptBuilder strings.Builder
for _, rule := range cc.rules {
promptBuilder.WriteString(rule.Content)
promptBuilder.WriteString("\n")
}
// Add skills section if there are any skills
if len(cc.skills.Skills) > 0 {
promptBuilder.WriteString("\n# Skills\n\n")
promptBuilder.WriteString("You have access to the following skills. Skills are specialized capabilities that provide ")
promptBuilder.WriteString("domain expertise, workflows, and procedural knowledge. When a task matches a skill's ")
promptBuilder.WriteString("description, you can load the full skill content by reading the SKILL.md file at the ")
promptBuilder.WriteString("location provided.\n\n")
skillsXML, err := cc.skills.AsXML()
if err != nil {
return nil, fmt.Errorf("failed to encode skills as XML: %w", err)
}
promptBuilder.WriteString(skillsXML)
promptBuilder.WriteString("\n\n")
}
promptBuilder.WriteString(cc.task.Content)
// Build and return the result
result := &Result{
Name: taskName,
Rules: cc.rules,
Task: cc.task,
Skills: cc.skills,
Tokens: cc.totalTokens,
Agent: cc.agent,
Prompt: promptBuilder.String(),
}
return result, nil
}
// isLocalPath checks if a path is a local file system path.
// Returns true for:
// - file:// URLs (e.g., file:///path/to/dir)
// - Absolute paths (e.g., /path/to/dir)
// - Relative paths (e.g., ./path or ../path)
// Returns false for remote protocols like git::, https://, s3::, etc.
func isLocalPath(path string) bool {
// Check if path starts with file:// protocol
if strings.HasPrefix(path, "file://") {
return true
}
// Check if it's an absolute or relative local path
// (no protocol prefix like git::, https://, s3::, etc.)
if !strings.Contains(path, "://") && !strings.Contains(path, "::") {
return true
}
return false
}
// normalizeLocalPath converts a local path to a usable file system path.
// For file:// URLs, it strips the protocol prefix.
// For other local paths, it returns them as-is.
func normalizeLocalPath(path string) string {
if strings.HasPrefix(path, "file://") {
return strings.TrimPrefix(path, "file://")
}
return path
}
func downloadDir(path string) string {
// hash the path and prepend it with a temporary directory
hash := sha256.Sum256([]byte(path))
tempDir := os.TempDir()
return filepath.Join(tempDir, fmt.Sprintf("%x", hash))
}
// parseManifestFile downloads a manifest file from a Go Getter URL and returns
// the list of search paths (one per line). Every line is included as-is without trimming.
func (cc *Context) parseManifestFile(ctx context.Context) ([]string, error) {
if cc.manifestURL == "" {
return nil, nil
}
manifestFile := downloadDir(cc.manifestURL)
// Download the manifest file using go-getter's GetFile function
// GetFile is specifically for downloading single files (not directories)
if _, err := getter.GetFile(ctx, manifestFile, cc.manifestURL); err != nil {
return nil, fmt.Errorf("failed to download manifest file %s: %w", cc.manifestURL, err)
}
defer os.RemoveAll(manifestFile)
cc.logger.Info("Downloaded manifest file", "path", manifestFile)
// Read and parse the manifest file
file, err := os.Open(manifestFile)
if err != nil {
return nil, fmt.Errorf("failed to open manifest file: %w", err)
}
defer file.Close()
var paths []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
paths = append(paths, scanner.Text())
}
if err := scanner.Err(); err != nil {
return nil, fmt.Errorf("failed to read manifest file: %w", err)
}
cc.logger.Info("Parsed manifest file", "url", cc.manifestURL, "paths", len(paths))
return paths, nil
}
func (cc *Context) downloadRemoteDirectories(ctx context.Context) error {
for _, path := range cc.searchPaths {
// If the path is local, use it directly without downloading
if isLocalPath(path) {
localPath := normalizeLocalPath(path)
cc.logger.Info("Using local directory", "path", localPath)
cc.downloadedPaths = append(cc.downloadedPaths, localPath)
continue
}
// Download remote directories
cc.logger.Info("Downloading remote directory", "path", path)
dst := downloadDir(path)
if _, err := getter.Get(ctx, dst, path); err != nil {
return fmt.Errorf("failed to download remote directory %s: %w", path, err)
}
cc.logger.Info("Downloaded to", "path", dst)
cc.downloadedPaths = append(cc.downloadedPaths, dst)
}
return nil
}
func (cc *Context) cleanupDownloadedDirectories() {
for _, path := range cc.searchPaths {
// Skip cleanup for local paths - they should not be deleted
if isLocalPath(path) {
continue
}
// Only clean up downloaded remote directories
dst := downloadDir(path)
if err := os.RemoveAll(dst); err != nil {
cc.logger.Error("Error cleaning up downloaded directory", "path", dst, "error", err)
}
}
}
func (cc *Context) findExecuteRuleFiles(ctx context.Context, homeDir string) error {
// Skip rule file discovery if bootstrap is disabled
if !cc.doBootstrap {
return nil
}
err := cc.visitMarkdownFiles(rulePaths, func(path string, baseFm *markdown.BaseFrontMatter) error {
var frontmatter markdown.RuleFrontMatter
md, err := markdown.ParseMarkdownFile(path, &frontmatter)
if err != nil {
return fmt.Errorf("failed to parse markdown file %s: %w", path, err)
}
// Automatically set ID to filename (without extension) if not set in frontmatter
if frontmatter.ID == "" {
frontmatter.ID = generateIDFromPath(path)
}
// Expand parameters only if expand is not explicitly set to false
var processedContent string
if shouldExpandParams(frontmatter.ExpandParams) {
processedContent, err = cc.expandParams(md.Content, nil)
if err != nil {
return fmt.Errorf("failed to expand parameters in file %s: %w", path, err)
}
} else {
processedContent = md.Content
}
tokens := tokencount.EstimateTokens(processedContent)
cc.rules = append(cc.rules, markdown.Markdown[markdown.RuleFrontMatter]{
FrontMatter: frontmatter,
Content: processedContent,
Tokens: tokens,
})
cc.totalTokens += tokens
// Get match reason to explain why this rule was included
_, reason := cc.includes.MatchesIncludes(*baseFm)
cc.logger.Info("Including rule file", "path", path, "reason", reason, "tokens", tokens)
if err := cc.runBootstrapScript(ctx, path, frontmatter.Bootstrap); err != nil {
return fmt.Errorf("failed to run bootstrap script: %w", err)
}
return nil
})
if err != nil {
return fmt.Errorf("failed to find and execute rule files: %w", err)
}
return nil
}
func (cc *Context) runBootstrapScript(ctx context.Context, path string, frontmatterBootstrap string) error {
// Prefer frontmatter bootstrap if present
if frontmatterBootstrap != "" {
cc.logger.Info("Running bootstrap from frontmatter", "path", path)
// Create a temporary file for the bootstrap script
tmpFile, err := os.CreateTemp("", "bootstrap-*.sh")
if err != nil {
return fmt.Errorf("failed to create temp file for bootstrap script from %s: %w", path, err)
}
tmpFilePath := tmpFile.Name()
defer os.Remove(tmpFilePath)
// Write the bootstrap script to the temp file
if _, err := tmpFile.WriteString(frontmatterBootstrap); err != nil {
tmpFile.Close()
return fmt.Errorf("failed to write bootstrap script from %s: %w", path, err)
}
tmpFile.Close()
// Make it executable
if err := os.Chmod(tmpFilePath, 0o755); err != nil {
return fmt.Errorf("failed to chmod bootstrap script from %s: %w", path, err)
}
cmd := exec.CommandContext(ctx, tmpFilePath)
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
if err := cc.cmdRunner(cmd); err != nil {
return fmt.Errorf("frontmatter bootstrap script failed for %s: %w", path, err)
}
return nil
}
// Fall back to file-based bootstrap
// Check for a bootstrap file named <markdown-file-without-md/mdc-suffix>-bootstrap
// For example, setup.md -> setup-bootstrap, setup.mdc -> setup-bootstrap
baseNameWithoutExt := strings.TrimSuffix(path, filepath.Ext(path))
bootstrapFilePath := baseNameWithoutExt + "-bootstrap"
if _, err := os.Stat(bootstrapFilePath); os.IsNotExist(err) {
// Doesn't exist, just skip.
return nil
} else if err != nil {
return fmt.Errorf("failed to stat bootstrap file %s: %w", bootstrapFilePath, err)
}
// Bootstrap file exists, make it executable and run it before printing content
if err := os.Chmod(bootstrapFilePath, 0o755); err != nil {
return fmt.Errorf("failed to chmod bootstrap file %s: %w", bootstrapFilePath, err)
}
cc.logger.Info("Running bootstrap script", "path", bootstrapFilePath)
cmd := exec.CommandContext(ctx, bootstrapFilePath)
cmd.Stdout = os.Stderr
cmd.Stderr = os.Stderr
if err := cc.cmdRunner(cmd); err != nil {
return fmt.Errorf("file-based bootstrap script failed for %s: %w", path, err)
}
return nil
}
// discoverSkills searches for skill directories and loads only their metadata (name and description)
// for progressive disclosure. Skills are folders containing a SKILL.md file.
func (cc *Context) discoverSkills() error {
// Skip skill discovery if bootstrap is disabled
if !cc.doBootstrap {
return nil
}
var skillPaths []string
for _, path := range cc.downloadedPaths {
skillPaths = append(skillPaths, skillSearchPaths(path)...)
}
for _, dir := range skillPaths {
if _, err := os.Stat(dir); os.IsNotExist(err) {
continue
} else if err != nil {
return fmt.Errorf("failed to stat skill directory %s: %w", dir, err)
}
// List all subdirectories in the skills directory
entries, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("failed to read skill directory %s: %w", dir, err)
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
skillDir := filepath.Join(dir, entry.Name())
skillFile := filepath.Join(skillDir, "SKILL.md")
// Check if SKILL.md exists
if _, err := os.Stat(skillFile); os.IsNotExist(err) {
continue
} else if err != nil {
return fmt.Errorf("failed to stat skill file %s: %w", skillFile, err)
}
// Parse only the frontmatter (metadata)
var frontmatter markdown.SkillFrontMatter
_, err := markdown.ParseMarkdownFile(skillFile, &frontmatter)
if err != nil {
return fmt.Errorf("failed to parse skill file %s: %w", skillFile, err)
}
// Check if the skill matches the selectors first (before validation)
matches, reason := cc.includes.MatchesIncludes(frontmatter.BaseFrontMatter)
if !matches {
// Log why this skill was skipped
if reason != "" {
cc.logger.Info("Skipping skill", "name", frontmatter.Name, "path", skillFile, "reason", reason)
}
continue
}
// Validate required fields and their lengths
if frontmatter.Name == "" {
return fmt.Errorf("skill %s missing required 'name' field", skillFile)
}
if len(frontmatter.Name) > 64 {
return fmt.Errorf("skill %s 'name' field must be 1-64 characters, got %d", skillFile, len(frontmatter.Name))
}
if frontmatter.Description == "" {
return fmt.Errorf("skill %s missing required 'description' field", skillFile)
}
if len(frontmatter.Description) > 1024 {
return fmt.Errorf("skill %s 'description' field must be 1-1024 characters, got %d", skillFile, len(frontmatter.Description))
}
// Get absolute path for the skill file
absPath, err := filepath.Abs(skillFile)
if err != nil {
return fmt.Errorf("failed to get absolute path for skill %s: %w", skillFile, err)
}
// Add skill to the collection
cc.skills.Skills = append(cc.skills.Skills, skills.Skill{
Name: frontmatter.Name,
Description: frontmatter.Description,
Location: absPath,
})
// Log with explanation of why skill was included
cc.logger.Info("Discovered skill", "name", frontmatter.Name, "reason", reason, "path", absPath)
}
}
return nil
}