-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcompose.go
More file actions
694 lines (637 loc) · 19.7 KB
/
compose.go
File metadata and controls
694 lines (637 loc) · 19.7 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
package main
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"strings"
"gopkg.in/yaml.v3"
)
// AgenticFile represents a parsed agentic content file (rule, skill, or agent).
type AgenticFile struct {
Kind string // "rule", "skill", "agent"
Name string // derived from filename/dirname
Path string // source path on disk
SourceDir string // for standard-layout skills: directory containing SKILL.md and supporting files
// Frontmatter fields (passthrough — each projector uses what it needs)
Description string `yaml:"description"`
Globs []string `yaml:"globs"` // rules: path/glob scoping
Model string `yaml:"model"` // agents: model preference
Tools []string `yaml:"tools"` // agents: tool allowlist
Skills []string `yaml:"skills"` // agents: declared skill dependencies
Agent string `yaml:"agent"` // skills: informational parent agent
UserInvocable *bool `yaml:"user-invocable"` // skills: show in autocomplete
AllowedTools []string `yaml:"allowed-tools"` // skills: tool allowlist
Type string `yaml:"type"` // skills: command type
// Body is everything after the frontmatter
Body string
}
// MCPServer represents an MCP server declaration.
type MCPServer struct {
Name string
Command string
Args []string
Env map[string]string
}
// MergedSet holds the result of merging bundle + global + project content.
// Rules, skills, and agents are independent peers — no ownership hierarchy.
type MergedSet struct {
Rules map[string]*AgenticFile
Skills map[string]*AgenticFile
Agents map[string]*AgenticFile
LoreMD string // accumulated LORE.md from all layers (bundle → global → project)
MCP []MCPServer
}
// parseAgenticFile parses a markdown file with YAML frontmatter.
func parseAgenticFile(path string, kind string) (*AgenticFile, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
af := &AgenticFile{
Kind: kind,
Path: path,
}
content := strings.ReplaceAll(string(data), "\r\n", "\n")
// Parse frontmatter if present
if strings.HasPrefix(content, "---\n") {
end := strings.Index(content[4:], "\n---")
if end >= 0 {
fmData := content[4 : 4+end]
af.Body = strings.TrimSpace(content[4+end+4:])
if err := yaml.Unmarshal([]byte(fmData), af); err != nil {
return nil, fmt.Errorf("parse frontmatter in %s: %w", path, err)
}
} else {
af.Body = strings.TrimSpace(content)
}
} else {
af.Body = strings.TrimSpace(content)
}
return af, nil
}
// readBundleSlugs reads enabled bundle slugs from .lore/config.json (project config).
// Returns slugs in priority order (first = lowest, last = highest).
func readBundleSlugs() []string {
return readBundleSlugsFrom("")
}
// readBundleSlugsFrom reads enabled bundle slugs from a specific project directory.
func readBundleSlugsFrom(projectDir string) []string {
data, err := os.ReadFile(filepath.Join(projectDir, ".lore", "config.json"))
if err != nil {
return nil
}
var cfg map[string]interface{}
if json.Unmarshal(stripJSONComments(data), &cfg) != nil {
return nil
}
return parseBundleSlugs(cfg)
}
// parseBundleSlugs extracts bundle slugs from a parsed config map.
func parseBundleSlugs(cfg map[string]interface{}) []string {
arr, ok := cfg["bundles"].([]interface{})
if !ok {
return nil
}
var slugs []string
for _, v := range arr {
if s, ok := v.(string); ok && s != "" {
slugs = append(slugs, s)
}
}
return slugs
}
// activeBundleDirs returns directories of all enabled bundles for the current project.
// Ordered by priority (first = lowest, last = highest).
func activeBundleDirs() []string {
return activeBundleDirsFrom("")
}
// activeBundleDirsFrom returns directories of all enabled bundles for a specific project.
func activeBundleDirsFrom(projectDir string) []string {
slugs := readBundleSlugsFrom(projectDir)
var dirs []string
for _, slug := range slugs {
if dir := bundleDirForSlug(slug); dir != "" {
dirs = append(dirs, dir)
}
}
return dirs
}
// bundleDirForSlug resolves a bundle slug to its installed directory.
// Checks XDG data path first, falls back to legacy ~/.<slug>/ for migration.
func bundleDirForSlug(slug string) string {
if slug == "" {
return ""
}
// XDG path: ~/.local/share/lore/bundles/<slug>/
dir := filepath.Join(bundlesPath(), slug)
if _, err := os.Stat(dir); err == nil {
return dir
}
// Legacy path: ~/.<slug>/
home, err := os.UserHomeDir()
if err != nil {
return ""
}
legacy := filepath.Join(home, "."+slug)
if _, err := os.Stat(legacy); err == nil {
return legacy
}
return ""
}
// readBundleManifest reads name and slug from manifest.json in the given bundle directory.
func readBundleManifest(pkgDir string) (name, slug string) {
data, err := os.ReadFile(filepath.Join(pkgDir, "manifest.json"))
if err != nil {
return "", ""
}
var manifest struct {
Name string `json:"name"`
Slug string `json:"slug"`
}
if json.Unmarshal(data, &manifest) != nil {
return "", ""
}
return manifest.Name, manifest.Slug
}
// readBundleName reads the "name" field from manifest.json in the given bundle directory.
func readBundleName(pkgDir string) string {
name, _ := readBundleManifest(pkgDir)
return name
}
// readBundleHookEntries reads hook behaviors from a bundle's manifest.json.
// Supports array format [{"name": "...", "script": "..."}] and legacy string format.
// Returns entries sorted by event then name.
func readBundleHookEntries(pkgDir string) []hookEntry {
data, err := os.ReadFile(filepath.Join(pkgDir, "manifest.json"))
if err != nil {
return nil
}
var manifest struct {
Hooks map[string]json.RawMessage `json:"hooks"`
}
if json.Unmarshal(data, &manifest) != nil {
return nil
}
var entries []hookEntry
for event, raw := range manifest.Hooks {
// Try array of behavior objects
var behaviors []struct {
Name string `json:"name"`
Script string `json:"script"`
}
if json.Unmarshal(raw, &behaviors) == nil && len(behaviors) > 0 {
for _, b := range behaviors {
entries = append(entries, hookEntry{event: event, name: b.Name})
}
continue
}
// Legacy: plain string — derive name from filename
var scriptPath string
if json.Unmarshal(raw, &scriptPath) == nil && scriptPath != "" {
base := filepath.Base(scriptPath)
entries = append(entries, hookEntry{event: event, name: strings.TrimSuffix(base, ".mjs")})
}
}
sort.Slice(entries, func(i, j int) bool {
if entries[i].event != entries[j].event {
return entries[i].event < entries[j].event
}
return entries[i].name < entries[j].name
})
return entries
}
// readHookEntriesFromDir scans a HOOKS directory for behavior scripts.
// New layout: HOOKS/<event>/<name>.mjs. Legacy: HOOKS/<event>.mjs.
// Returns entries sorted by event then name.
func readHookEntriesFromDir(dir string) []hookEntry {
var entries []hookEntry
for _, event := range allHookEvents {
// New layout: HOOKS/<event>/*.mjs
eventDir := filepath.Join(dir, event)
if dirEntries, err := os.ReadDir(eventDir); err == nil {
for _, e := range dirEntries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".mjs") {
continue
}
name := strings.TrimSuffix(e.Name(), ".mjs")
entries = append(entries, hookEntry{event: event, name: name})
}
continue
}
// Legacy: HOOKS/<event>.mjs
p := filepath.Join(dir, event+".mjs")
if _, err := os.Stat(p); err == nil {
entries = append(entries, hookEntry{event: event, name: event})
}
}
return entries
}
// BundleTUIPage represents a TUI page declared by a bundle.
type BundleTUIPage struct {
Name string
Script string // absolute path to script
BundleSlug string
}
// readBundleTUIPages reads TUI page declarations from all enabled bundle manifests.
func readBundleTUIPages() []BundleTUIPage {
var pages []BundleTUIPage
for _, dir := range activeBundleDirs() {
data, err := os.ReadFile(filepath.Join(dir, "manifest.json"))
if err != nil {
continue
}
var manifest struct {
Slug string `json:"slug"`
TUI struct {
Pages []struct {
Name string `json:"name"`
Script string `json:"script"`
} `json:"pages"`
} `json:"tui"`
}
if json.Unmarshal(data, &manifest) != nil {
continue
}
for _, p := range manifest.TUI.Pages {
pages = append(pages, BundleTUIPage{
Name: p.Name,
Script: filepath.Join(dir, p.Script),
BundleSlug: manifest.Slug,
})
}
}
return pages
}
// readMCPDir scans a directory for MCP server JSON declarations.
// Each *.json file is one server; filename (minus .json) is the server name.
// Relative paths in args are resolved relative to the JSON file's directory.
func readMCPDir(dir string) []MCPServer {
entries, err := os.ReadDir(dir)
if err != nil {
return nil
}
var servers []MCPServer
for _, e := range entries {
if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") {
continue
}
data, err := os.ReadFile(filepath.Join(dir, e.Name()))
if err != nil {
continue
}
var s struct {
Command string `json:"command"`
Args []string `json:"args"`
Env map[string]string `json:"env"`
}
if json.Unmarshal(data, &s) != nil || s.Command == "" {
continue
}
resolved := make([]string, len(s.Args))
for i, arg := range s.Args {
if !filepath.IsAbs(arg) && !strings.HasPrefix(arg, "-") {
candidate := filepath.Join(dir, arg)
if _, err := os.Stat(candidate); err == nil {
resolved[i] = candidate
continue
}
}
resolved[i] = arg
}
name := strings.TrimSuffix(e.Name(), ".json")
servers = append(servers, MCPServer{
Name: name,
Command: s.Command,
Args: resolved,
Env: s.Env,
})
}
return servers
}
// readBundleMCP reads MCP server declarations from all enabled bundles' MCP/ directories.
// Higher-priority bundles override lower-priority ones by server name.
func readBundleMCP() []MCPServer {
mcpMap := make(map[string]MCPServer)
for _, pkgDir := range activeBundleDirs() {
for _, s := range readMCPDir(filepath.Join(pkgDir, "MCP")) {
mcpMap[s.Name] = s
}
}
return sortedMCP(mcpMap)
}
// sortedMCP returns a sorted slice from a name→server map.
func sortedMCP(m map[string]MCPServer) []MCPServer {
names := sortedKeys(m)
servers := make([]MCPServer, len(names))
for i, name := range names {
servers[i] = m[name]
}
return servers
}
// BundleInfo represents a discovered bundle on disk.
type BundleInfo struct {
Slug string
Name string
Version string
Dir string // absolute path to bundle home directory
Active bool // true if this is the currently active bundle
}
// discoverBundles scans for installed bundles in XDG data path and legacy home dirs.
func discoverBundles() []BundleInfo {
activeSlugs := make(map[string]bool)
for _, s := range readBundleSlugs() {
activeSlugs[s] = true
}
seen := make(map[string]bool)
var bundles []BundleInfo
addBundle := func(dir string) {
data, err := os.ReadFile(filepath.Join(dir, "manifest.json"))
if err != nil {
return
}
var manifest struct {
Slug string `json:"slug"`
Name string `json:"name"`
Version string `json:"version"`
}
if json.Unmarshal(data, &manifest) != nil || manifest.Slug == "" {
return
}
if seen[manifest.Slug] {
return // XDG takes precedence over legacy
}
seen[manifest.Slug] = true
bundles = append(bundles, BundleInfo{
Slug: manifest.Slug,
Name: manifest.Name,
Version: manifest.Version,
Dir: dir,
Active: activeSlugs[manifest.Slug],
})
}
// XDG path: ~/.local/share/lore/bundles/*/
bp := bundlesPath()
if entries, err := os.ReadDir(bp); err == nil {
for _, e := range entries {
dir := filepath.Join(bp, e.Name())
info, err := os.Stat(dir)
if err != nil || !info.IsDir() {
continue
}
addBundle(dir)
}
}
// Legacy path: ~/.<name>/ (for migration)
home, _ := os.UserHomeDir()
if home != "" {
if entries, err := os.ReadDir(home); err == nil {
for _, e := range entries {
if !strings.HasPrefix(e.Name(), ".") {
continue
}
dir := filepath.Join(home, e.Name())
info, err := os.Stat(dir)
if err != nil || !info.IsDir() {
continue
}
addBundle(dir)
}
}
}
sort.Slice(bundles, func(i, j int) bool {
return bundles[i].Slug < bundles[j].Slug
})
return bundles
}
// scanAgenticDir scans a directory for rules, skills, or agents.
func scanAgenticDir(baseDir string) (rules, skills, agents map[string]*AgenticFile, err error) {
rules = make(map[string]*AgenticFile)
skills = make(map[string]*AgenticFile)
agents = make(map[string]*AgenticFile)
// Rules: baseDir/RULES/*.md
rulesDir := filepath.Join(baseDir, "RULES")
if entries, e := os.ReadDir(rulesDir); e == nil {
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") {
continue
}
name := strings.TrimSuffix(entry.Name(), ".md")
af, e := parseAgenticFile(filepath.Join(rulesDir, entry.Name()), "rule")
if e != nil {
continue // silently skip malformed files
}
af.Name = name
rules[name] = af
}
}
// Skills: baseDir/SKILLS/<name>/SKILL.md (directory layout only)
skillsDir := filepath.Join(baseDir, "SKILLS")
if entries, e := os.ReadDir(skillsDir); e == nil {
for _, entry := range entries {
if !entry.IsDir() {
continue
}
skillDir := filepath.Join(skillsDir, entry.Name())
skillFile := filepath.Join(skillDir, "SKILL.md")
if _, e := os.Stat(skillFile); e != nil {
continue
}
name := entry.Name()
af, e := parseAgenticFile(skillFile, "skill")
if e != nil {
continue // silently skip malformed files
}
af.Name = name
af.SourceDir = skillDir
skills[name] = af
}
}
// Agents: baseDir/AGENTS/*.md
agentsDir := filepath.Join(baseDir, "AGENTS")
if entries, e := os.ReadDir(agentsDir); e == nil {
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".md") {
continue
}
name := strings.TrimSuffix(entry.Name(), ".md")
af, e := parseAgenticFile(filepath.Join(agentsDir, entry.Name()), "agent")
if e != nil {
continue // silently skip malformed files
}
af.Name = name
agents[name] = af
}
}
return rules, skills, agents, nil
}
// getPolicy returns the inherit policy for an item, falling back to defaultPolicy.
func getPolicy(inheritCfg map[string]map[string]string, kind, name, defaultPolicy string) string {
if inheritCfg != nil {
if kindMap, ok := inheritCfg[kind]; ok {
if policy, ok := kindMap[name]; ok {
return policy
}
}
}
return defaultPolicy
}
// defaultForSource returns the default inherit policy for a given source layer.
// Bundle items default to "defer" (auto-included). Global items default to "off" (opt-in).
func defaultForSource(source string) string {
if source == "bundle" {
return "defer"
}
return "off"
}
// readLoreMD reads a LORE.md file and returns its trimmed content, or "" if absent/empty.
func readLoreMD(path string) string {
data, err := os.ReadFile(path)
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
// mergeAgenticSets merges four layers of content:
// 1. Bundle (lowest) — defaults from the active bundle
// 2. Global (~/.config/lore/) — operator preferences
// 3. Project (.lore/) — project overrides
// 4. Harness (highest) — binary-managed, clobbers everything
//
// globalDir is the global config directory (~/.config/lore/).
// projectDir is the project lore directory (<root>/.lore/).
// LORE.md is accumulated from all layers (bundle → global → project).
// Rules, skills, and agents use inherit.json policies with source-dependent
// defaults: bundle items default to "defer", global items default to "off".
func mergeAgenticSets(globalDir, projectDir string) (*MergedSet, error) {
ms := &MergedSet{
Rules: make(map[string]*AgenticFile),
Skills: make(map[string]*AgenticFile),
Agents: make(map[string]*AgenticFile),
}
// Read inheritance config (.lore/inherit.json).
projectRoot := filepath.Dir(projectDir)
inheritCfg := readInheritConfig(projectRoot)
nonce := readOrCreateNonce(projectRoot)
// Accumulate LORE.md from all layers (bundle → global → project)
var loreParts []string
// Harness content is injected after all layers merge (see below).
// Layer 1 (lowest): Bundle content — all enabled bundles in priority order.
// Later bundles override earlier ones for same-named items.
for _, pkgDir := range activeBundleDirs() {
pkgRules, pkgSkills, pkgAgents, err := scanAgenticDir(pkgDir)
if err == nil {
for k, v := range pkgRules {
if p := getPolicy(inheritCfg, "rules", k, "defer"); p == "defer" || p == "overwrite" {
ms.Rules[k] = v
}
}
for k, v := range pkgSkills {
if p := getPolicy(inheritCfg, "skills", k, "defer"); p == "defer" || p == "overwrite" {
ms.Skills[k] = v
}
}
for k, v := range pkgAgents {
if p := getPolicy(inheritCfg, "agents", k, "defer"); p == "defer" || p == "overwrite" {
ms.Agents[k] = v
}
}
}
// Bundle LORE.md
if content := readLoreMD(filepath.Join(pkgDir, "LORE.md")); content != "" {
content = strings.ReplaceAll(content, "{{NONCE}}", nonce)
label := "Bundle"
if name := readBundleName(pkgDir); name != "" {
label = name
}
loreParts = append(loreParts, "# "+label+"\n\n"+content)
}
}
// Layer 2: Global content — default policy "off"
if _, err := os.Stat(globalDir); err == nil {
rules, skills, agents, err := scanAgenticDir(globalDir)
if err != nil {
return nil, fmt.Errorf("scan global content: %w", err)
}
for k, v := range rules {
if p := getPolicy(inheritCfg, "rules", k, "off"); p == "defer" || p == "overwrite" {
ms.Rules[k] = v
}
}
for k, v := range skills {
if p := getPolicy(inheritCfg, "skills", k, "off"); p == "defer" || p == "overwrite" {
ms.Skills[k] = v
}
}
for k, v := range agents {
if p := getPolicy(inheritCfg, "agents", k, "off"); p == "defer" || p == "overwrite" {
ms.Agents[k] = v
}
}
}
// Global LORE.md
if content := readLoreMD(filepath.Join(globalDir, "LORE.md")); content != "" {
loreParts = append(loreParts, "# Global\n\n"+content)
}
// Layer 3 (highest): Project content — always included,
// except when a bundle/global item has "overwrite" policy.
if _, err := os.Stat(projectDir); err == nil {
rules, skills, agents, err := scanAgenticDir(projectDir)
if err != nil {
return nil, fmt.Errorf("scan project content: %w", err)
}
for k, v := range rules {
if getPolicy(inheritCfg, "rules", k, "off") == "overwrite" {
continue
}
ms.Rules[k] = v
}
for k, v := range skills {
if getPolicy(inheritCfg, "skills", k, "off") == "overwrite" {
continue
}
ms.Skills[k] = v
}
for k, v := range agents {
if getPolicy(inheritCfg, "agents", k, "off") == "overwrite" {
continue
}
ms.Agents[k] = v
}
}
// Project LORE.md
if content := readLoreMD(filepath.Join(projectDir, "LORE.md")); content != "" {
loreParts = append(loreParts, "# Project\n\n"+content)
}
ms.LoreMD = strings.Join(loreParts, "\n\n")
// MCP: three-layer merge — bundles (lowest) → global → project (highest).
// Override by server name at each layer.
mcpMap := make(map[string]MCPServer)
for _, s := range readBundleMCP() {
mcpMap[s.Name] = s
}
for _, s := range readMCPDir(filepath.Join(globalPath(), "MCP")) {
mcpMap[s.Name] = s
}
for _, s := range readMCPDir(filepath.Join(projectDir, "MCP")) {
mcpMap[s.Name] = s
}
ms.MCP = sortedMCP(mcpMap)
// Harness content — injected last, clobbers everything.
// Binary-managed content that no other layer can override.
harnessDir := filepath.Join(globalDir, ".harness")
if _, err := os.Stat(harnessDir); err == nil {
hRules, hSkills, hAgents, _ := scanAgenticDir(harnessDir)
for k, v := range hRules {
ms.Rules[k] = v
}
for k, v := range hSkills {
ms.Skills[k] = v
}
for k, v := range hAgents {
ms.Agents[k] = v
}
}
return ms, nil
}