Skip to content

mission control for agent skills

Implement local and remote source discovery in Inventory

alvinreal9fed0324da45
diff --git a/internal/actions/actions.go b/internal/actions/actions.go
index 2db343e..8059e8b 100644
--- a/internal/actions/actions.go
+++ b/internal/actions/actions.go
@@ -142,6 +142,35 @@ func bulkBatch(skills []*model.Skill, resolve SkillsResolver, actionID string) (
return batch, true, ""
}
+func ForAvailableSkill(source, name string) []CommandPreview {
+ return ForAvailableSkillWithResolver(source, name, ResolveSkillsCommand)
+}
+
+func ForAvailableSkillWithResolver(source, name string, resolve SkillsResolver) []CommandPreview {
+ if !safeExecValue(source) || strings.HasPrefix(source, "-") {
+ return []CommandPreview{unavailablePreview("Install selected skill", "source is empty, option-like, or contains unsafe characters")}
+ }
+ if !safeExecValue(name) || strings.HasPrefix(name, "-") {
+ return []CommandPreview{unavailablePreview("Install selected skill", "skill name is empty, option-like, or contains unsafe characters")}
+ }
+
+ if resolve == nil {
+ resolve = ResolveSkillsCommand
+ }
+ available, reason := HasSkillsOrNpx()
+ program, baseArgs := resolve()
+
+ args := append([]string{}, baseArgs...)
+ args = append(args, "add", source, "--skill", name, "--yes")
+
+ preview := newPreview("install_skill", "Install selected skill", program, args, "Install this skill to project.", true, true, false, "yes")
+ if !available {
+ preview.Available = false
+ preview.Reason = reason
+ }
+ return []CommandPreview{preview}
+}
+
func ForSkillWithResolver(sk *model.Skill, resolve SkillsResolver) []CommandPreview {
if sk == nil {
return nil
diff --git a/internal/actions/actions_test.go b/internal/actions/actions_test.go
index a97c253..7aa95f7 100644
--- a/internal/actions/actions_test.go
+++ b/internal/actions/actions_test.go
@@ -288,3 +288,45 @@ func TestMissingDepsDisablesActions(t *testing.T) {
t.Errorf("expected app-level init to be unavailable when deps are missing")
}
}
+
+func TestForAvailableSkill(t *testing.T) {
+ LookPath = func(name string) (string, error) {
+ return "/usr/bin/" + name, nil
+ }
+ previews := ForAvailableSkill("owner/repo", "test-skill")
+ if len(previews) != 1 {
+ t.Fatalf("expected 1 install preview, got %d", len(previews))
+ }
+ inst := previews[0]
+ if inst.ID != "install_skill" || !inst.Mutates || !inst.RequiresConfirm {
+ t.Errorf("unexpected install preview: %+v", inst)
+ }
+ if !containsArg(inst.Exec.Args, "owner/repo") || !containsArg(inst.Exec.Args, "test-skill") {
+ t.Errorf("expected source and skill name in args, got %+v", inst.Exec.Args)
+ }
+}
+
+func TestForAvailableSkillUnsafeRejection(t *testing.T) {
+ cases := []struct {
+ source string
+ name string
+ }{
+ {"--bad-source", "name"},
+ {"source", "--bad-name"},
+ {"", "name"},
+ {"source", ""},
+ {"source\x1b", "name"},
+ {"source", "name\n"},
+ {"bad\x00source", "name"},
+ {"source", "name\r"},
+ }
+ for _, tc := range cases {
+ previews := ForAvailableSkill(tc.source, tc.name)
+ if len(previews) != 1 {
+ t.Fatalf("expected 1 preview, got %d", len(previews))
+ }
+ if previews[0].Available {
+ t.Errorf("expected preview to be unavailable for source=%q name=%q", tc.source, tc.name)
+ }
+ }
+}
diff --git a/internal/tui/tui.go b/internal/tui/tui.go
index a32ff60..69c3483 100644
--- a/internal/tui/tui.go
+++ b/internal/tui/tui.go
@@ -1,8 +1,11 @@
package tui
import (
+ "errors"
"fmt"
+ "os"
"os/exec"
+ "path/filepath"
"sort"
"strings"
@@ -15,6 +18,7 @@ import (
"lazyskills/internal/agents"
"lazyskills/internal/compat"
"lazyskills/internal/display"
+ "lazyskills/internal/frontmatter"
"lazyskills/internal/model"
"lazyskills/internal/runner"
"lazyskills/internal/scan"
@@ -36,6 +40,29 @@ const (
focusPreview
)
+type DiscoveryStatus string
+
+const (
+ DiscoveryNotChecked DiscoveryStatus = "not_checked"
+ DiscoveryLoading DiscoveryStatus = "loading"
+ DiscoveryReady DiscoveryStatus = "ready"
+ DiscoveryFailed DiscoveryStatus = "failed"
+)
+
+type DiscoveredSkill struct {
+ Name string
+ Description string
+ Source string
+ SkillPath string
+ Preview string
+}
+
+type SourceDiscovery struct {
+ Status DiscoveryStatus
+ Skills []DiscoveredSkill
+ Error string
+}
+
type appModel struct {
cwd string
result model.ScanResult
@@ -65,6 +92,7 @@ type appModel struct {
helpOpen bool
focus focusState
collapsedGroups map[string]bool
+ discovery map[string]SourceDiscovery
}
type paneLayout struct {
@@ -99,6 +127,7 @@ var (
errorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("203"))
warningStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("214"))
runExec = runner.OSRunner{}.Run
+ gitClone = defaultGitClone
// Action Mode UI Polish Styles
actionTitleStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("230")).Background(lipgloss.Color("62")).Padding(0, 1)
@@ -123,6 +152,12 @@ type snapshotMsg struct {
err error
}
+type discoveryResultMsg struct {
+ groupName string
+ skills []DiscoveredSkill
+ err error
+}
+
type actionResultMsg struct {
result runner.Result
mutates bool
@@ -143,6 +178,7 @@ func newModel(cwd string) appModel {
metadataViewport: viewport.New(0, 0),
previewViewport: viewport.New(0, 0),
collapsedGroups: make(map[string]bool),
+ discovery: make(map[string]SourceDiscovery),
}
}
@@ -183,6 +219,21 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.pruneSelected()
m.actionResult = nil
m.syncViewport()
+ case discoveryResultMsg:
+ disc := SourceDiscovery{
+ Status: DiscoveryReady,
+ Skills: msg.skills,
+ }
+ if msg.err != nil {
+ disc.Status = DiscoveryFailed
+ disc.Error = msg.err.Error()
+ }
+ if m.discovery == nil {
+ m.discovery = make(map[string]SourceDiscovery)
+ }
+ m.discovery[msg.groupName] = disc
+ m.clampSelection()
+ m.syncViewport()
case actionResultMsg:
m.running = false
m.runningTitle = ""
@@ -377,6 +428,10 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
} else {
m.collapseGroup(row.groupName)
}
+ } else if row.isAvailable {
+ m.focus = focusPreview
+ m.detailsFocused = true
+ m.syncViewport()
} else {
m.detailModal = true
m.detailsFocused = true
@@ -386,19 +441,29 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
}
case "o":
rows := m.visibleRows()
- if len(rows) > 0 && m.selected < len(rows) && !rows[m.selected].isHeader {
+ if len(rows) > 0 && m.selected < len(rows) && !rows[m.selected].isHeader && !rows[m.selected].isAvailable {
return m.startCurrentSkillActionByID("open_skill")
}
case "u":
rows := m.visibleRows()
- if len(rows) > 0 && m.selected < len(rows) && !rows[m.selected].isHeader {
+ if len(rows) > 0 && m.selected < len(rows) && !rows[m.selected].isHeader && !rows[m.selected].isAvailable {
return m.startActionByID(preferredUpdateActionID(m.selectedCount()))
}
case "x":
rows := m.visibleRows()
- if len(rows) > 0 && m.selected < len(rows) && !rows[m.selected].isHeader {
+ if len(rows) > 0 && m.selected < len(rows) && !rows[m.selected].isHeader && !rows[m.selected].isAvailable {
return m.startActionByID(preferredRemoveActionID(m.selectedCount()))
}
+ case "d":
+ if m.focus == focusSkills {
+ rows := m.visibleRows()
+ if len(rows) > 0 && m.selected >= 0 && m.selected < len(rows) {
+ row := rows[m.selected]
+ if row.isHeader {
+ return m.startDiscovery(row.groupName)
+ }
+ }
+ }
case "/":
m.searching = true
case "r":
@@ -584,6 +649,9 @@ func (m appModel) currentActions() []actions.CommandPreview {
if row.isHeader {
return m.sourceActions(row.groupName)
}
+ if row.isAvailable {
+ return actions.ForAvailableSkill(row.groupName, row.discoveredSkill.Name)
+ }
return actions.ForSkill(row.skill)
}
@@ -680,6 +748,11 @@ func confirmationAccepted(input, confirmValue string) bool {
}
func (m appModel) executeAction(action actions.CommandPreview) (tea.Model, tea.Cmd) {
+ if action.ID == "source_discover" {
+ m.commands = false
+ m.actionResult = nil
+ return m.startDiscovery(action.ConfirmValue)
+ }
if action.Exec.Internal == "refresh" {
m.actionResult = nil
return m, loadSnapshot(m.cwd)
@@ -801,10 +874,12 @@ func (m *appModel) syncViewport() {
}
type skillsRow struct {
- isHeader bool
- groupName string
- skill *model.Skill
- skillIndex int
+ isHeader bool
+ isAvailable bool
+ groupName string
+ skill *model.Skill
+ discoveredSkill *DiscoveredSkill
+ skillIndex int
}
func (m appModel) visibleRows() []skillsRow {
@@ -814,6 +889,9 @@ func (m appModel) visibleRows() []skillsRow {
for i, skill := range items {
group := listGroupLabel(skill)
if group != previousGroup {
+ if previousGroup != "" && !m.isCollapsed(previousGroup) {
+ rows = append(rows, m.getAvailableRowsForGroup(previousGroup)...)
+ }
rows = append(rows, skillsRow{
isHeader: true,
groupName: group,
@@ -831,6 +909,29 @@ func (m appModel) visibleRows() []skillsRow {
skillIndex: i,
})
}
+ if previousGroup != "" && !m.isCollapsed(previousGroup) {
+ rows = append(rows, m.getAvailableRowsForGroup(previousGroup)...)
+ }
+ return rows
+}
+
+func (m appModel) getAvailableRowsForGroup(groupName string) []skillsRow {
+ var rows []skillsRow
+ disc, ok := m.discovery[groupName]
+ if !ok || disc.Status != DiscoveryReady {
+ return nil
+ }
+ for i, ds := range disc.Skills {
+ if !m.isSkillInstalled(ds.Name, groupName) {
+ rows = append(rows, skillsRow{
+ isHeader: false,
+ isAvailable: true,
+ groupName: groupName,
+ discoveredSkill: &disc.Skills[i],
+ skillIndex: -1,
+ })
+ }
+ }
return rows
}
@@ -1032,6 +1133,29 @@ func (m appModel) sourceActions(group string) []actions.CommandPreview {
previews[i].ConfirmValue = group
}
}
+
+ discoverable, reason := m.isSourceDiscoverable(group)
+
+ _, _, isRemote := parseRemoteGitHubSource(group)
+ title := "Check local source for available skills"
+ desc := "Scan the local source root for uninstalled skills."
+ if isRemote {
+ title = "Check remote source for available skills"
+ desc = "Clone and scan the remote repository for available skills."
+ }
+ discPreview := actions.CommandPreview{
+ ID: "source_discover",
+ Title: title,
+ Description: desc,
+ Command: fmt.Sprintf("discover %s", group),
+ Exec: actions.ExecSpec{Internal: "discover", Args: []string{group}},
+ RequiresConfirm: false,
+ Available: discoverable,
+ Reason: reason,
+ ConfirmValue: group, // Reused to pass group name
+ }
+ previews = append(previews, discPreview)
+
return previews
}
@@ -1371,6 +1495,15 @@ func (m appModel) listPane(height, width int) string {
} else {
line = dimStyle.Render(truncate(headerText, width))
}
+ } else if row.isAvailable {
+ ds := row.discoveredSkill
+ coreLabel := fmt.Sprintf(" + %s [available]", ds.Name)
+ truncatedCore := truncate(coreLabel, width)
+ if idx == selectedRow {
+ line = selectedStyle.Render(truncatedCore)
+ } else {
+ line = dimStyle.Render(truncatedCore)
+ }
} else {
view := display.Skill(row.skill)
mark := " "
@@ -1632,6 +1765,20 @@ func (m appModel) metadataLines(width int) []string {
return lines
}
+ if row.isAvailable {
+ ds := row.discoveredSkill
+ lines := []string{
+ formatMetaLine("Skill:", ds.Name, width),
+ formatMetaLine("Status:", "available", width),
+ formatMetaLine("Source:", ds.Source, width),
+ }
+ if ds.SkillPath != "" {
+ lines = append(lines, formatMetaLine("Path:", ds.SkillPath, width))
+ }
+ lines = append(lines, "", wrapText(ds.Description, width))
+ return lines
+ }
+
view := display.Skill(row.skill)
lines := []string{
formatMetaLine("Scope:", string(view.Scope), width),
@@ -1730,15 +1877,69 @@ func (m appModel) previewLines(width int) []string {
row := rows[m.selected]
if row.isHeader {
+ disc, discOk := m.discovery[row.groupName]
+ lines := []string{
+ sectionHeaderStyle.Render("Installed Skills:"),
+ }
skills := m.sourceGroupSkills(row.groupName)
- lines := []string{"Installed Skills:"}
- for _, sk := range skills {
- lines = append(lines, fmt.Sprintf("• %s [%s]", sk.Name, scopeBadge(string(sk.Scope))))
+ if len(skills) == 0 {
+ lines = append(lines, " No installed skills under this source.")
+ } else {
+ for _, sk := range skills {
+ scopeBadgeStr := "[P]"
+ if sk.Scope == model.ScopeGlobal {
+ scopeBadgeStr = "[G]"
+ }
+ lines = append(lines, fmt.Sprintf(" • %s %s", sk.Name, scopeBadgeStr))
+ }
}
+
+ lines = append(lines, "")
+
+ _, _, isRemote := parseRemoteGitHubSource(row.groupName)
+ statusHeader := sectionHeaderStyle.Render("Available Skills:")
+ if !discOk {
+ if isRemote {
+ lines = append(lines, statusHeader, " Remote source discovery not run yet. Press 'd' to scan.")
+ } else {
+ lines = append(lines, statusHeader, " Local source discovery not run yet. Press 'd' to scan.")
+ }
+ } else {
+ switch disc.Status {
+ case DiscoveryLoading:
+ if isRemote {
+ lines = append(lines, statusHeader, " Cloning and scanning remote repository...")
+ } else {
+ lines = append(lines, statusHeader, " Scanning local checkout...")
+ }
+ case DiscoveryFailed:
+ lines = append(lines, statusHeader, fmt.Sprintf(" Discovery failed: %s", disc.Error))
+ case DiscoveryReady:
+ var avails []DiscoveredSkill
+ for _, ds := range disc.Skills {
+ if !m.isSkillInstalled(ds.Name, row.groupName) {
+ avails = append(avails, ds)
+ }
+ }
+ if len(avails) == 0 {
+ if isRemote {
+ lines = append(lines, statusHeader, " All discovered skills from this remote repository are installed.")
+ } else {
+ lines = append(lines, statusHeader, " All discovered skills from this local source are installed.")
+ }
+ } else {
+ lines = append(lines, statusHeader)
+ for _, av := range avails {
+ lines = append(lines, fmt.Sprintf(" + %s", av.Name))
+ }
+ }
+ }
+ }
+
lines = append(lines,
"",
- "Only installed skills are shown.",
- "Source discovery can be added later.",
+ dimStyle.Render("Discovery shows installed and available skills from this source."),
+ dimStyle.Render("Use d to refresh local/remote source discovery."),
)
var wrapped []string
for _, line := range lines {
@@ -1747,6 +1948,23 @@ func (m appModel) previewLines(width int) []string {
return wrapped
}
+ if row.isAvailable {
+ ds := row.discoveredSkill
+ if ds.Preview != "" {
+ var lines []string
+ previewLines := strings.Split(ds.Preview, "\n")
+ for _, line := range previewLines {
+ lines = append(lines, wrapText(line, width))
+ }
+ return lines
+ }
+ return []string{
+ dimStyle.Render("No preview content found for this available skill."),
+ "",
+ dimStyle.Render("Press 'c' to open actions and install it."),
+ }
+ }
+
view := display.Skill(row.skill)
if view.Preview == "" {
return []string{dimStyle.Render("No preview available for this skill.")}
@@ -1766,7 +1984,7 @@ func (m appModel) detailLines(width int) []string {
return m.metadataLines(width)
}
row := rows[m.selected]
- if row.isHeader {
+ if row.isHeader || row.isAvailable {
return m.metadataLines(width)
}
view := display.Skill(row.skill)
@@ -2030,14 +2248,17 @@ func (m appModel) footerText(width int) string {
} else {
// focusSkills
rows := m.visibleRows()
- var selectedIsHeader bool
if len(rows) > 0 && m.selected >= 0 && m.selected < len(rows) {
- selectedIsHeader = rows[m.selected].isHeader
- }
- if selectedIsHeader {
- text = "enter toggle · c source actions · / search · f scope · a agent · r reload · ? help"
+ row := rows[m.selected]
+ if row.isHeader {
+ text = "enter toggle · c source actions · h/- collapse · l/+ expand · d discover · ? help"
+ } else if row.isAvailable {
+ text = "enter preview · c install actions · ? help"
+ } else {
+ text = "enter open · c skill actions · o edit · u update · x remove · ? help"
+ }
} else {
- text = "enter open · c skill actions · / search · f scope · a agent · r reload · ? help"
+ text = "enter open · c skill actions · o edit · u update · x remove · ? help"
}
}
return dimStyle.Render(truncate(text, width))
@@ -2056,12 +2277,12 @@ func (m appModel) helpModalOverlay(layout appLayout) string {
titleStyle.Render(" LazySkills Keyboard Help "),
"",
sectionHeaderStyle.Render("Navigation & Focus:"),
- " ↑/↓, j/k Move selection (Skills focus) or scroll (Metadata/Preview)",
- " 1 / 2 / 3 Focus Skills (1), Metadata (2), or Preview (3) pane",
+ " ↑/↓, j/k Move selection (Inventory focus) or scroll (Metadata/Preview)",
+ " 1 / 2 / 3 Focus Inventory (1), Metadata (2), or Preview (3) pane",
" tab / shift-tab Cycle focus forward / backward through panes",
- " ← / → Move focus backward / forward outside Skills; jump groups in Skills",
- " h / l Collapse / expand current source group in Skills",
- " [ / ] Jump to previous / next source group in Skills",
+ " ← / → Move focus backward / forward outside Inventory; jump groups in Inventory",
+ " h / l Collapse / expand current source group in Inventory",
+ " [ / ] Jump to previous / next source group in Inventory",
"",
sectionHeaderStyle.Render("Filters:"),
" P / G Filter Project-only / Global-only scope",
@@ -2070,12 +2291,13 @@ func (m appModel) helpModalOverlay(layout appLayout) string {
" / Initiate text search",
"",
sectionHeaderStyle.Render("Actions & Selection:"),
- " enter Open scrollable read-only skill detail modal",
+ " enter Open detail modal (Skill) or toggle collapse (Source row)",
" space Mark / unmark selected skill for bulk actions",
" s Mark all skills in the current source group",
" o Open selected skill directly in editor",
" c Open command picker menu",
" u / x Quick reinstall-update / remove for selection",
+ " d Check local or remote source for available skills (Source row)",
" r Refresh scan snapshot",
"",
sectionHeaderStyle.Render("Safety & Modals:"),
@@ -2628,3 +2850,351 @@ func truncateTitle(s string, width int) string {
}
return string(runes[:width-1]) + "…"
}
+
+func (m appModel) isSkillInstalled(name string, group string) bool {
+ norm := compat.NormalizeName(name)
+ for _, sk := range m.result.Skills {
+ if listGroupLabel(sk) == group && compat.NormalizeName(sk.Name) == norm {
+ return true
+ }
+ }
+ return false
+}
+
+func (m appModel) resolveGroupSourceRoot(groupName string) string {
+ if st, err := os.Stat(groupName); err == nil && st.IsDir() {
+ return groupName
+ }
+ skills := m.sourceGroupSkills(groupName)
+ for _, sk := range skills {
+ if root := resolveSourceRoot(sk); root != "" {
+ if st, err := os.Stat(root); err == nil && st.IsDir() {
+ return root
+ }
+ }
+ }
+ return ""
+}
+
+func resolveSourceRoot(skill *model.Skill) string {
+ if skill == nil {
+ return ""
+ }
+ pathOnDisk := skill.CanonicalPath
+ if pathOnDisk == "" {
+ for _, op := range skill.ObservedPaths {
+ if op.Path != "" {
+ pathOnDisk = op.Path
+ break
+ }
+ }
+ }
+ if pathOnDisk == "" {
+ return ""
+ }
+
+ relPath := ""
+ sourceType := ""
+ if skill.LocalLock != nil {
+ relPath = skill.LocalLock.SkillPath
+ sourceType = skill.LocalLock.SourceType
+ } else if skill.GlobalLock != nil {
+ relPath = skill.GlobalLock.SkillPath
+ sourceType = skill.GlobalLock.SourceType
+ }
+
+ relPath = strings.TrimSuffix(relPath, "/SKILL.md")
+ relPath = strings.TrimSuffix(relPath, "SKILL.md")
+ relPath = strings.Trim(relPath, "/")
+
+ if relPath == "" {
+ absDisk := filepath.Clean(pathOnDisk)
+ if st, err := os.Stat(filepath.Join(absDisk, ".git")); err == nil && st.IsDir() {
+ return absDisk
+ }
+ if sourceType == "local" || sourceType == "directory" {
+ return absDisk
+ }
+ return ""
+ }
+
+ absDisk := filepath.Clean(pathOnDisk)
+ relClean := filepath.Clean(relPath)
+
+ if strings.HasSuffix(absDisk, relClean) {
+ root := strings.TrimSuffix(absDisk, relClean)
+ root = filepath.Clean(root)
+ if st, err := os.Stat(filepath.Join(root, ".git")); err == nil && st.IsDir() {
+ return root
+ }
+ if sourceType == "local" || sourceType == "directory" {
+ return root
+ }
+ }
+
+ return ""
+}
+
+func discoverSourceSkills(sourceRoot string) ([]DiscoveredSkill, error) {
+ var discovered []DiscoveredSkill
+ err := filepath.WalkDir(sourceRoot, func(path string, d os.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if d.IsDir() {
+ name := d.Name()
+ if name == ".git" || name == "node_modules" || name == "vendor" || name == ".agents" || name == ".slim" {
+ return filepath.SkipDir
+ }
+ rel, relErr := filepath.Rel(sourceRoot, path)
+ if relErr == nil {
+ depth := len(strings.Split(filepath.ToSlash(rel), "/"))
+ if depth > 5 {
+ return filepath.SkipDir
+ }
+ }
+ return nil
+ }
+
+ if d.Name() == "SKILL.md" {
+ doc, parseErr := frontmatter.ParseFile(path)
+ if parseErr == nil {
+ contentBytes, readErr := os.ReadFile(path)
+ previewStr := ""
+ if readErr == nil {
+ previewStr = string(contentBytes)
+ }
+ discovered = append(discovered, DiscoveredSkill{
+ Name: compat.SanitizeMetadata(doc.Name),
+ Description: compat.SanitizeMetadata(doc.Description),
+ SkillPath: compat.SanitizeMetadata(path),
+ Preview: compat.SanitizePreviewContent(previewStr),
+ })
+ }
+ }
+ return nil
+ })
+ return discovered, err
+}
+
+func rawSourceRef(skill *model.Skill) string {
+ if skill == nil {
+ return ""
+ }
+ if skill.Scope == model.ScopeProject && skill.LocalLock != nil {
+ return skill.LocalLock.Ref
+ }
+ if skill.Scope == model.ScopeGlobal && skill.GlobalLock != nil {
+ return skill.GlobalLock.Ref
+ }
+ if skill.LocalLock != nil {
+ return skill.LocalLock.Ref
+ }
+ if skill.GlobalLock != nil {
+ return skill.GlobalLock.Ref
+ }
+ return ""
+}
+
+func (m appModel) isSourceDiscoverable(group string) (bool, string) {
+ if root := m.resolveGroupSourceRoot(group); root != "" {
+ return true, ""
+ }
+
+ refToCheck := ""
+ if idx := strings.Index(group, "#"); idx != -1 {
+ refToCheck = group[idx+1:]
+ }
+ if refToCheck != "" && !isSafeGitHubRef(refToCheck) {
+ return false, "ref contains unsafe or invalid characters"
+ }
+
+ _, ref, ok := parseRemoteGitHubSource(group)
+ if !ok {
+ return false, "requires a local checkout or a remote GitHub source"
+ }
+
+ if ref == "" {
+ for _, sk := range m.sourceGroupSkills(group) {
+ rawRef := rawSourceRef(sk)
+ if rawRef != "" {
+ if !isSafeGitHubRef(rawRef) {
+ return false, "ref contains unsafe or invalid characters"
+ }
+ ref = rawRef
+ break
+ }
+ }
+ }
+ if ref != "" && !isSafeGitHubRef(ref) {
+ return false, "ref contains unsafe or invalid characters"
+ }
+
+ return true, ""
+}
+
+func (m appModel) startDiscovery(groupName string) (tea.Model, tea.Cmd) {
+ if m.discovery == nil {
+ m.discovery = make(map[string]SourceDiscovery)
+ }
+ m.discovery[groupName] = SourceDiscovery{
+ Status: DiscoveryLoading,
+ }
+
+ discoverable, reason := m.isSourceDiscoverable(groupName)
+ if !discoverable {
+ m.discovery[groupName] = SourceDiscovery{
+ Status: DiscoveryFailed,
+ Error: "Discovery failed: " + reason + ".",
+ }
+ return m, nil
+ }
+
+ root := m.resolveGroupSourceRoot(groupName)
+ if root != "" {
+ return m, func() tea.Msg {
+ skills, err := discoverSourceSkills(root)
+ for i := range skills {
+ skills[i].Source = compat.SanitizeMetadata(groupName)
+ }
+ return discoveryResultMsg{
+ groupName: groupName,
+ skills: skills,
+ err: err,
+ }
+ }
+ }
+
+ url, ref, _ := parseRemoteGitHubSource(groupName)
+ if ref == "" {
+ for _, sk := range m.sourceGroupSkills(groupName) {
+ rawRef := rawSourceRef(sk)
+ if rawRef != "" {
+ ref = rawRef
+ break
+ }
+ }
+ }
+
+ return m, func() tea.Msg {
+ tempDir, err := os.MkdirTemp("", "lazyskills-discover-*")
+ if err != nil {
+ return discoveryResultMsg{
+ groupName: groupName,
+ err: fmt.Errorf("failed to create temporary directory: %w", err),
+ }
+ }
+ defer os.RemoveAll(tempDir)
+
+ cleanRef := compat.SanitizeMetadata(ref)
+ if err := gitClone(url, cleanRef, tempDir); err != nil {
+ return discoveryResultMsg{
+ groupName: groupName,
+ err: errors.New(compat.SanitizeMetadata(err.Error())),
+ }
+ }
+
+ skills, err := discoverSourceSkills(tempDir)
+ for i := range skills {
+ skills[i].Source = compat.SanitizeMetadata(groupName)
+ }
+ return discoveryResultMsg{
+ groupName: groupName,
+ skills: skills,
+ err: err,
+ }
+ }
+}
+
+func parseRemoteGitHubSource(source string) (url string, ref string, ok bool) {
+ repoPart := source
+ if idx := strings.Index(source, "#"); idx != -1 {
+ repoPart = source[:idx]
+ ref = source[idx+1:]
+ }
+
+ if strings.HasPrefix(repoPart, "https://github.com/") {
+ repoPart = strings.TrimPrefix(repoPart, "https://github.com/")
+ } else if strings.HasPrefix(repoPart, "github:") {
+ repoPart = strings.TrimPrefix(repoPart, "github:")
+ }
+
+ repoPart = strings.TrimSuffix(repoPart, ".git")
+
+ parts := strings.Split(repoPart, "/")
+ if len(parts) != 2 {
+ return "", "", false
+ }
+ owner, repo := parts[0], parts[1]
+ if !isSafeGitHubToken(owner) || !isSafeGitHubToken(repo) {
+ return "", "", false
+ }
+
+ if ref != "" && !isSafeGitHubRef(ref) {
+ return "", "", false
+ }
+
+ return fmt.Sprintf("https://github.com/%s/%s", owner, repo), ref, true
+}
+
+func isSafeGitHubToken(s string) bool {
+ if s == "" || strings.HasPrefix(s, "-") {
+ return false
+ }
+ for _, r := range s {
+ if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.') {
+ return false
+ }
+ }
+ return true
+}
+
+func isSafeGitHubRef(s string) bool {
+ if s == "" || strings.HasPrefix(s, "-") || strings.HasPrefix(s, "/") || strings.HasSuffix(s, "/") {
+ return false
+ }
+ if strings.Contains(s, "..") || strings.Contains(s, "@{") || strings.Contains(s, "\\") {
+ return false
+ }
+ for _, r := range s {
+ if !((r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' || r == '/') {
+ return false
+ }
+ if r < 32 || r == 127 {
+ return false
+ }
+ }
+ return true
+}
+
+func defaultGitClone(url, ref, tempDir string) error {
+ if _, err := exec.LookPath("git"); err != nil {
+ return fmt.Errorf("git executable not found in PATH")
+ }
+
+ if ref != "" {
+ cmd := exec.Command("git", "clone", "--depth", "1", "--branch", ref, url, tempDir)
+ if err := cmd.Run(); err == nil {
+ return nil
+ }
+ }
+
+ cmd := exec.Command("git", "clone", "--depth", "1", url, tempDir)
+ if err := cmd.Run(); err != nil {
+ return fmt.Errorf("failed to clone repository: %w", err)
+ }
+
+ if ref != "" {
+ checkoutCmd := exec.Command("git", "checkout", ref)
+ checkoutCmd.Dir = tempDir
+ if err := checkoutCmd.Run(); err != nil {
+ fetchCmd := exec.Command("git", "fetch", "--depth", "1", "origin", ref)
+ fetchCmd.Dir = tempDir
+ _ = fetchCmd.Run()
+ if err := checkoutCmd.Run(); err != nil {
+ return fmt.Errorf("failed to checkout ref %q: %w", ref, err)
+ }
+ }
+ }
+ return nil
+}
diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go
index 205d059..cfa71d9 100644
--- a/internal/tui/tui_test.go
+++ b/internal/tui/tui_test.go
@@ -3,6 +3,8 @@ package tui
import (
"errors"
"fmt"
+ "os"
+ "path/filepath"
"strings"
"testing"
@@ -1523,7 +1525,7 @@ func TestRichSourceInventoryMetadataAndActions(t *testing.T) {
if !strings.Contains(prevJoined, "• One [P]") || !strings.Contains(prevJoined, "• Two [G]") {
t.Errorf("expected skills listed with scope badges in preview, got %q", prevJoined)
}
- if !strings.Contains(prevJoined, "Only installed skills are shown.") || !strings.Contains(prevJoined, "Source discovery can be added later.") {
+ if !strings.Contains(prevJoined, "Discovery shows installed and available skills from this source.") || !strings.Contains(prevJoined, "Use d to refresh local/remote source discovery.") {
t.Errorf("expected preview footnotes in preview, got %q", prevJoined)
}
@@ -1554,3 +1556,362 @@ func TestRichSourceInventoryMetadataAndActions(t *testing.T) {
t.Errorf("did not expect skill-scoped actions for source row, got %+v", acts)
}
}
+
+func TestRemoteDiscoverySuccess(t *testing.T) {
+ oldGitClone := gitClone
+ defer func() { gitClone = oldGitClone }()
+
+ var capturedURL, capturedRef string
+ gitClone = func(url, ref, tempDir string) error {
+ capturedURL = url
+ capturedRef = ref
+ skillPath := filepath.Join(tempDir, "SKILL.md")
+ skillContent := "---\nname: \"Remote Skill\"\ndescription: \"Remote description\"\n---\nRemote preview content"
+ if err := os.WriteFile(skillPath, []byte(skillContent), 0o644); err != nil {
+ return err
+ }
+ return nil
+ }
+
+ m := appModel{
+ width: 120, height: 32, selected: 0,
+ result: model.ScanResult{
+ Skills: []*model.Skill{
+ {Name: "Existing", Scope: model.ScopeProject, LocalLock: &model.LocalLockEntry{Source: "owner/repo"}},
+ },
+ },
+ }
+ m.syncViewport()
+
+ updated, cmd := m.startDiscovery("owner/repo")
+ if cmd == nil {
+ t.Fatal("expected discovery cmd")
+ }
+ msg := cmd()
+ updated, _ = updated.Update(msg)
+ next := updated.(appModel)
+
+ if next.discovery["owner/repo"].Status != DiscoveryReady {
+ t.Fatalf("expected discovery ready, got status %s, error: %s", next.discovery["owner/repo"].Status, next.discovery["owner/repo"].Error)
+ }
+ if capturedURL != "https://github.com/owner/repo" {
+ t.Fatalf("expected URL to be https://github.com/owner/repo, got %s", capturedURL)
+ }
+ if capturedRef != "" {
+ t.Fatalf("expected empty captured ref, got %s", capturedRef)
+ }
+
+ rows := next.visibleRows()
+ var foundAvailable bool
+ for _, r := range rows {
+ if r.isAvailable && r.discoveredSkill != nil && r.discoveredSkill.Name == "Remote Skill" {
+ foundAvailable = true
+ break
+ }
+ }
+ if !foundAvailable {
+ t.Fatalf("expected available row for 'Remote Skill', but not found in rows: %#v", rows)
+ }
+}
+
+func TestRemoteDiscoveryFailure(t *testing.T) {
+ oldGitClone := gitClone
+ defer func() { gitClone = oldGitClone }()
+
+ gitClone = func(url, ref, tempDir string) error {
+ return fmt.Errorf("network connection error")
+ }
+
+ m := appModel{
+ width: 120, height: 32, selected: 0,
+ result: model.ScanResult{
+ Skills: []*model.Skill{
+ {Name: "Existing", Scope: model.ScopeProject, LocalLock: &model.LocalLockEntry{Source: "owner/repo"}},
+ },
+ },
+ }
+ updated, cmd := m.startDiscovery("owner/repo")
+ if cmd == nil {
+ t.Fatal("expected discovery cmd")
+ }
+ msg := cmd()
+ updated, _ = updated.Update(msg)
+ next := updated.(appModel)
+
+ disc := next.discovery["owner/repo"]
+ if disc.Status != DiscoveryFailed {
+ t.Fatalf("expected status failed, got %s", disc.Status)
+ }
+ if !strings.Contains(disc.Error, "network connection error") {
+ t.Fatalf("expected error to contain network connection error, got %s", disc.Error)
+ }
+}
+
+func TestRemoteDiscoveryRejectsUnsafe(t *testing.T) {
+ cases := []struct {
+ source string
+ safe bool
+ }{
+ {"owner/repo", true},
+ {"github:owner/repo", true},
+ {"https://github.com/owner/repo", true},
+ {"https://github.com/owner/repo.git", true},
+ {"owner/repo#ref", true},
+ {"owner/repo#ref-name_123.4", true},
+ {"owner/repo#ref/with/slash", true},
+ {"-owner/repo", false},
+ {"owner/-repo", false},
+ {"owner/repo#--ref", false},
+ {"owner/repo;-somecmd", false},
+ {"owner/repo/sub", false},
+ {"https://gitlab.com/owner/repo", false},
+ }
+ for _, tc := range cases {
+ _, _, ok := parseRemoteGitHubSource(tc.source)
+ if ok != tc.safe {
+ t.Errorf("expected %q safe=%v, got %v", tc.source, tc.safe, ok)
+ }
+ }
+}
+
+func TestIsSafeGitHubRef(t *testing.T) {
+ cases := []struct {
+ ref string
+ safe bool
+ }{
+ {"main", true},
+ {"v1.2.3", true},
+ {"feature/branch-name_1", true},
+ {"", false},
+ {"-branch", false},
+ {"/branch", false},
+ {"branch/", false},
+ {"branch..name", false},
+ {"branch@{1}", false},
+ {"branch\\name", false},
+ {"branch\x00name", false},
+ {"branch\x1bname", false},
+ {"branch name", false},
+ }
+ for _, tc := range cases {
+ ok := isSafeGitHubRef(tc.ref)
+ if ok != tc.safe {
+ t.Errorf("expected ref %q safe=%v, got %v", tc.ref, tc.safe, ok)
+ }
+ }
+}
+
+func TestRemoteDiscoverySanitization(t *testing.T) {
+ oldGitClone := gitClone
+ defer func() { gitClone = oldGitClone }()
+
+ gitClone = func(url, ref, tempDir string) error {
+ skillPath := filepath.Join(tempDir, "SKILL.md")
+ skillContent := "---\nname: \"Bad\\u001b[31m Skill\"\ndescription: \"Bad\\u001b[31m Description\"\n---\nBad\x1b[31m preview content"
+ if err := os.WriteFile(skillPath, []byte(skillContent), 0o644); err != nil {
+ return err
+ }
+ return nil
+ }
+
+ m := appModel{
+ width: 120, height: 32, selected: 0,
+ result: model.ScanResult{
+ Skills: []*model.Skill{
+ {Name: "Existing", Scope: model.ScopeProject, LocalLock: &model.LocalLockEntry{Source: "owner/repo"}},
+ },
+ },
+ }
+ m.syncViewport()
+
+ updated, cmd := m.startDiscovery("owner/repo")
+ if cmd == nil {
+ t.Fatal("expected discovery cmd")
+ }
+ msg := cmd()
+ updated, _ = updated.Update(msg)
+ next := updated.(appModel)
+
+ disc := next.discovery["owner/repo"]
+ if disc.Status != DiscoveryReady {
+ t.Fatalf("expected discovery ready, got status %s, error: %s", disc.Status, disc.Error)
+ }
+
+ if len(disc.Skills) != 1 {
+ t.Fatalf("expected 1 skill, got %d", len(disc.Skills))
+ }
+
+ ds := disc.Skills[0]
+ if strings.Contains(ds.Name, "\x1b") {
+ t.Errorf("expected name to be sanitized, got %q", ds.Name)
+ }
+ if strings.Contains(ds.Description, "\x1b") {
+ t.Errorf("expected description to be sanitized, got %q", ds.Description)
+ }
+ if strings.Contains(ds.Preview, "\x1b") {
+ t.Errorf("expected preview to be sanitized, got %q", ds.Preview)
+ }
+}
+
+func TestRemoteDiscoveryUnsafeRef(t *testing.T) {
+ m := appModel{
+ width: 120, height: 32, selected: 0,
+ result: model.ScanResult{
+ Skills: []*model.Skill{
+ {Name: "Existing", Scope: model.ScopeProject, LocalLock: &model.LocalLockEntry{Source: "owner/repo"}},
+ },
+ },
+ }
+ // Verify that starting discovery on an unsafe ref fails immediately with a clear message
+ updated, cmd := m.startDiscovery("owner/repo#--unsafe-ref")
+ if cmd != nil {
+ t.Fatal("expected discovery cmd to be nil for unsafe ref")
+ }
+ next := updated.(appModel)
+ disc := next.discovery["owner/repo#--unsafe-ref"]
+ if disc.Status != DiscoveryFailed {
+ t.Fatalf("expected status failed, got %s", disc.Status)
+ }
+ if !strings.Contains(disc.Error, "ref contains unsafe or invalid characters") {
+ t.Fatalf("expected error to mention unsafe ref, got %s", disc.Error)
+ }
+}
+
+func TestRemoteDiscoveryUnsafeFallbackRef(t *testing.T) {
+ oldGitClone := gitClone
+ defer func() { gitClone = oldGitClone }()
+
+ calledClone := false
+ gitClone = func(url, ref, tempDir string) error {
+ calledClone = true
+ return nil
+ }
+
+ m := appModel{
+ width: 120, height: 32, selected: 0,
+ result: model.ScanResult{
+ Skills: []*model.Skill{
+ {
+ Name: "Existing",
+ Scope: model.ScopeProject,
+ LocalLock: &model.LocalLockEntry{Source: "owner/repo", Ref: "--unsafe-ref"},
+ },
+ },
+ },
+ }
+ // Trigger discovery on "owner/repo" which has an unsafe fallback ref
+ updated, cmd := m.startDiscovery("owner/repo")
+ if cmd != nil {
+ t.Fatal("expected discovery cmd to be nil for unsafe fallback ref")
+ }
+ next := updated.(appModel)
+ disc := next.discovery["owner/repo"]
+ if disc.Status != DiscoveryFailed {
+ t.Fatalf("expected status failed, got %s", disc.Status)
+ }
+ if !strings.Contains(disc.Error, "ref contains unsafe or invalid characters") {
+ t.Fatalf("expected error to mention unsafe ref, got %s", disc.Error)
+ }
+ if calledClone {
+ t.Fatal("gitClone was called but it should not have been")
+ }
+}
+
+func TestSourceDiscoverActionAvailability(t *testing.T) {
+ m := appModel{
+ width: 120, height: 32, selected: 0,
+ result: model.ScanResult{
+ Skills: []*model.Skill{
+ {Name: "Untracked", Scope: model.ScopeProject}, // Custom / untracked group
+ },
+ },
+ }
+ m.syncViewport()
+ acts := m.sourceActions("Custom / untracked")
+ var discAction *actions.CommandPreview
+ for _, act := range acts {
+ if act.ID == "source_discover" {
+ discAction = &act
+ break
+ }
+ }
+ if discAction == nil {
+ t.Fatal("expected source_discover action to be present")
+ }
+ if discAction.Available {
+ t.Fatal("expected discovery to be unavailable for untracked/custom group")
+ }
+ if !strings.Contains(discAction.Reason, "requires a local checkout") {
+ t.Fatalf("expected meaningful reason, got %q", discAction.Reason)
+ }
+ if discAction.Command != "discover Custom / untracked" {
+ t.Fatalf("expected Command text 'discover Custom / untracked', got %q", discAction.Command)
+ }
+}
+
+func TestRemoteDiscoveryRawFallbackRefBypass(t *testing.T) {
+ oldGitClone := gitClone
+ defer func() { gitClone = oldGitClone }()
+
+ calledClone := false
+ gitClone = func(url, ref, tempDir string) error {
+ calledClone = true
+ return nil
+ }
+
+ // Case 1: Ref contains control/escape char \x1b
+ m1 := appModel{
+ width: 120, height: 32, selected: 0,
+ result: model.ScanResult{
+ Skills: []*model.Skill{
+ {
+ Name: "Existing",
+ Scope: model.ScopeProject,
+ LocalLock: &model.LocalLockEntry{Source: "owner/repo", Ref: "main\x1b"},
+ },
+ },
+ },
+ }
+ updated1, cmd1 := m1.startDiscovery("owner/repo")
+ if cmd1 != nil {
+ t.Fatal("expected discovery cmd to be nil for unsafe fallback ref containing escape char")
+ }
+ next1 := updated1.(appModel)
+ disc1 := next1.discovery["owner/repo"]
+ if disc1.Status != DiscoveryFailed {
+ t.Fatalf("expected status failed, got %s", disc1.Status)
+ }
+ if !strings.Contains(disc1.Error, "ref contains unsafe or invalid characters") {
+ t.Fatalf("expected error to mention unsafe ref, got %s", disc1.Error)
+ }
+
+ // Case 2: Ref contains newline char \n
+ m2 := appModel{
+ width: 120, height: 32, selected: 0,
+ result: model.ScanResult{
+ Skills: []*model.Skill{
+ {
+ Name: "Existing",
+ Scope: model.ScopeProject,
+ LocalLock: &model.LocalLockEntry{Source: "owner/repo", Ref: "main\nnext"},
+ },
+ },
+ },
+ }
+ updated2, cmd2 := m2.startDiscovery("owner/repo")
+ if cmd2 != nil {
+ t.Fatal("expected discovery cmd to be nil for unsafe fallback ref containing newline")
+ }
+ next2 := updated2.(appModel)
+ disc2 := next2.discovery["owner/repo"]
+ if disc2.Status != DiscoveryFailed {
+ t.Fatalf("expected status failed, got %s", disc2.Status)
+ }
+ if !strings.Contains(disc2.Error, "ref contains unsafe or invalid characters") {
+ t.Fatalf("expected error to mention unsafe ref, got %s", disc2.Error)
+ }
+
+ if calledClone {
+ t.Fatal("gitClone was called but it should not have been")
+ }
+}