Skip to content

mission control for agent skills

Initial LazySkills implementation

Alvin Unreala646ed80e233
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b8a41a6
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+# BEGIN oh-my-opencode-slim clonedeps
+.slim/clonedeps/repos/
+# END oh-my-opencode-slim clonedeps
+
+.slim/deepwork/
diff --git a/.ignore b/.ignore
new file mode 100644
index 0000000..cc57efa
--- /dev/null
+++ b/.ignore
@@ -0,0 +1,12 @@
+# BEGIN oh-my-opencode-slim clonedeps
+!.slim/
+!.slim/clonedeps.json
+!.slim/clonedeps/
+!.slim/clonedeps/repos/
+!.slim/clonedeps/repos/**
+.slim/clonedeps/repos/**/.git/
+.slim/clonedeps/repos/**/.git/**
+# END oh-my-opencode-slim clonedeps
+
+!.slim/deepwork/
+!.slim/deepwork/**
diff --git a/.slim/clonedeps.json b/.slim/clonedeps.json
new file mode 100644
index 0000000..1f7f077
--- /dev/null
+++ b/.slim/clonedeps.json
@@ -0,0 +1,15 @@
+{
+ "version": "1.0.0",
+ "updatedAt": "2026-06-17T00:00:00.000Z",
+ "dependencies": [
+ {
+ "name": "vercel-labs/skills",
+ "resolvedVersion": "be0dd25b4a8665894a56f45ef582cc02ca802c39",
+ "repoUrl": "https://github.com/vercel-labs/skills.git",
+ "ref": "be0dd25b4a8665894a56f45ef582cc02ca802c39",
+ "path": ".slim/clonedeps/repos/vercel-labs__skills",
+ "packagePath": null,
+ "reason": "Skill definitions and examples are useful reference material for the new project."
+ }
+ ]
+}
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 0000000..45c1fa4
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,6 @@
+## Cloned Dependency Source
+
+Read-only dependency source repositories are available under
+`.slim/clonedeps/repos/` for inspection. Do not edit these clones.
+
+- `.slim/clonedeps/repos/vercel-labs__skills/` — `vercel-labs/skills` at `be0dd25b4a8665894a56f45ef582cc02ca802c39`; reference source for skill definitions and examples for the new project.
diff --git a/cmd/lazyskills/main.go b/cmd/lazyskills/main.go
new file mode 100644
index 0000000..4550387
--- /dev/null
+++ b/cmd/lazyskills/main.go
@@ -0,0 +1,71 @@
+package main
+
+import (
+ "encoding/json"
+ "flag"
+ "fmt"
+ "os"
+
+ "lazyskills/internal/scan"
+ "lazyskills/internal/tui"
+)
+
+func main() {
+ if err := run(os.Args[1:]); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+func run(args []string) error {
+ if len(args) == 0 {
+ cwd, err := os.Getwd()
+ if err != nil {
+ return err
+ }
+ return tui.Run(cwd)
+ }
+ if args[0] != "scan" {
+ fs := flag.NewFlagSet("lazyskills", flag.ContinueOnError)
+ fs.SetOutput(os.Stderr)
+ cwd := fs.String("cwd", "", "project working directory")
+ if err := fs.Parse(args); err != nil {
+ return err
+ }
+ if fs.NArg() > 0 {
+ return fmt.Errorf("usage: lazyskills [--cwd <path>] | lazyskills scan --json [--cwd <path>]")
+ }
+ if *cwd == "" {
+ var err error
+ *cwd, err = os.Getwd()
+ if err != nil {
+ return err
+ }
+ }
+ return tui.Run(*cwd)
+ }
+ fs := flag.NewFlagSet("scan", flag.ContinueOnError)
+ fs.SetOutput(os.Stderr)
+ jsonOut := fs.Bool("json", false, "output JSON")
+ cwd := fs.String("cwd", "", "project working directory")
+ if err := fs.Parse(args[1:]); err != nil {
+ return err
+ }
+ if !*jsonOut {
+ return fmt.Errorf("scan currently requires --json")
+ }
+ if *cwd == "" {
+ var err error
+ *cwd, err = os.Getwd()
+ if err != nil {
+ return err
+ }
+ }
+ result, err := scan.Run(*cwd)
+ if err != nil {
+ return err
+ }
+ enc := json.NewEncoder(os.Stdout)
+ enc.SetIndent("", " ")
+ return enc.Encode(result)
+}
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..43c7e05
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,34 @@
+module lazyskills
+
+go 1.26.3
+
+require (
+ github.com/charmbracelet/bubbletea v1.3.10
+ github.com/charmbracelet/lipgloss v1.1.0
+ gopkg.in/yaml.v3 v3.0.1
+)
+
+require (
+ github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect
+ github.com/charmbracelet/bubbles v1.0.0 // indirect
+ github.com/charmbracelet/colorprofile v0.4.1 // indirect
+ github.com/charmbracelet/x/ansi v0.11.6 // indirect
+ github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
+ github.com/charmbracelet/x/term v0.2.2 // indirect
+ github.com/clipperhouse/displaywidth v0.9.0 // indirect
+ github.com/clipperhouse/stringish v0.1.1 // indirect
+ github.com/clipperhouse/uax29/v2 v2.5.0 // indirect
+ github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
+ github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/mattn/go-localereader v0.0.1 // indirect
+ github.com/mattn/go-runewidth v0.0.19 // indirect
+ github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect
+ github.com/muesli/cancelreader v0.2.2 // indirect
+ github.com/muesli/reflow v0.3.0 // indirect
+ github.com/muesli/termenv v0.16.0 // indirect
+ github.com/rivo/uniseg v0.4.7 // indirect
+ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
+ golang.org/x/sys v0.38.0 // indirect
+ golang.org/x/text v0.3.8 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..52de7c2
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,74 @@
+github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=
+github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=
+github.com/charmbracelet/bubbles v1.0.0 h1:12J8/ak/uCZEMQ6KU7pcfwceyjLlWsDLAxB5fXonfvc=
+github.com/charmbracelet/bubbles v1.0.0/go.mod h1:9d/Zd5GdnauMI5ivUIVisuEm3ave1XwXtD1ckyV6r3E=
+github.com/charmbracelet/bubbletea v1.3.10 h1:otUDHWMMzQSB0Pkc87rm691KZ3SWa4KUlvF9nRvCICw=
+github.com/charmbracelet/bubbletea v1.3.10/go.mod h1:ORQfo0fk8U+po9VaNvnV95UPWA1BitP1E0N6xJPlHr4=
+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=
+github.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=
+github.com/charmbracelet/colorprofile v0.4.1 h1:a1lO03qTrSIRaK8c3JRxJDZOvhvIeSco3ej+ngLk1kk=
+github.com/charmbracelet/colorprofile v0.4.1/go.mod h1:U1d9Dljmdf9DLegaJ0nGZNJvoXAhayhmidOdcBwAvKk=
+github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
+github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
+github.com/charmbracelet/x/ansi v0.10.1 h1:rL3Koar5XvX0pHGfovN03f5cxLbCF2YvLeyz7D2jVDQ=
+github.com/charmbracelet/x/ansi v0.10.1/go.mod h1:3RQDQ6lDnROptfpWuUVIUG64bD2g2BgntdxH0Ya5TeE=
+github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=
+github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
+github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=
+github.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=
+github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
+github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
+github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
+github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
+github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
+github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
+github.com/clipperhouse/displaywidth v0.9.0 h1:Qb4KOhYwRiN3viMv1v/3cTBlz3AcAZX3+y9OLhMtAtA=
+github.com/clipperhouse/displaywidth v0.9.0/go.mod h1:aCAAqTlh4GIVkhQnJpbL0T/WfcrJXHcj8C0yjYcjOZA=
+github.com/clipperhouse/stringish v0.1.1 h1:+NSqMOr3GR6k1FdRhhnXrLfztGzuG+VuFDfatpWHKCs=
+github.com/clipperhouse/stringish v0.1.1/go.mod h1:v/WhFtE1q0ovMta2+m+UbpZ+2/HEXNWYXQgCt4hdOzA=
+github.com/clipperhouse/uax29/v2 v2.5.0 h1:x7T0T4eTHDONxFJsL94uKNKPHrclyFI0lm7+w94cO8U=
+github.com/clipperhouse/uax29/v2 v2.5.0/go.mod h1:Wn1g7MK6OoeDT0vL+Q0SQLDz/KpfsVRgg6W7ihQeh4g=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f h1:Y/CXytFA4m6baUTXGLOoWe4PQhGxaX0KpnayAqC48p4=
+github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f/go.mod h1:vw97MGsxSvLiUE2X8qFplwetxpGLQrlU1Q9AUEIzCaM=
+github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=
+github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
+github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
+github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=
+github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=
+github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
+github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
+github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
+github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
+github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=
+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=
+github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
+github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
+github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s=
+github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8=
+github.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=
+github.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=
+github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
+github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
+github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
+github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
+github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
+golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561 h1:MDc5xs78ZrZr3HMQugiXOAkSZtfTpbJLDr/lwfgO53E=
+golang.org/x/exp v0.0.0-20220909182711-5c715a9e8561/go.mod h1:cyybsKvd6eL0RnXn6p/Grxp8F5bW7iYuBgsNCOHpMYE=
+golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI=
+golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k=
+golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
+golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/text v0.3.8 h1:nAL+RVCQ9uMn3vJZbV+MRnydTJFPf8qqY42YiA6MrqY=
+golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
+gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
diff --git a/internal/actions/actions.go b/internal/actions/actions.go
new file mode 100644
index 0000000..9cae5b5
--- /dev/null
+++ b/internal/actions/actions.go
@@ -0,0 +1,209 @@
+package actions
+
+import (
+ "path/filepath"
+ "strings"
+
+ "lazyskills/internal/compat"
+ "lazyskills/internal/model"
+)
+
+type CommandPreview struct {
+ Title string
+ Program string
+ Args []string
+ Command string
+ Description string
+ Mutates bool
+ Available bool
+ Reason string
+}
+
+func ForSkill(sk *model.Skill) []CommandPreview {
+ if sk == nil {
+ return nil
+ }
+ previews := []CommandPreview{
+ newPreview("Refresh LazySkills", "lazyskills", nil, "Refresh is handled inside the TUI with r; this command reopens the dashboard.", false),
+ }
+
+ if addSource, skillFilter, ok, reason := addIdentity(sk); ok {
+ args := []string{"skills", "add", addSource, "--skill", skillFilter}
+ if sk.Scope == model.ScopeGlobal {
+ args = append(args, "-g")
+ }
+ preview := newPreview("Reinstall/update selected skill", "npx", args, "Mutating preview only. Reinstall/update this skill via the official skills CLI.", true)
+ previews = append(previews, preview)
+ } else {
+ previews = append(previews, unavailablePreview("Reinstall/update selected skill", reason))
+ }
+
+ if target, ok, reason := removeIdentity(sk); ok {
+ args := []string{"skills", "remove", target}
+ if sk.Scope == model.ScopeGlobal {
+ args = append(args, "-g")
+ }
+ previews = append(previews, newPreview("Remove selected skill", "npx", args, "Mutating preview only. Remove this installed skill via the official skills CLI after confirmation outside LazySkills.", true))
+ } else {
+ previews = append(previews, unavailablePreview("Remove selected skill", reason))
+ }
+ return previews
+}
+
+func newPreview(title, program string, args []string, description string, mutates bool) CommandPreview {
+ program = safeToken(program)
+ safeArgs := make([]string, 0, len(args))
+ for _, arg := range args {
+ safeArgs = append(safeArgs, compat.SanitizeMetadata(arg))
+ }
+ preview := CommandPreview{Title: title, Program: program, Args: safeArgs, Description: description, Mutates: mutates, Available: true}
+ preview.Command = renderCommand(program, safeArgs)
+ return preview
+}
+
+func unavailablePreview(title, reason string) CommandPreview {
+ return CommandPreview{Title: title, Available: false, Reason: compat.SanitizeMetadata(firstNonEmpty(reason, "not enough safe identity data to build this command"))}
+}
+
+func addIdentity(sk *model.Skill) (source string, skillFilter string, ok bool, reason string) {
+ source, ref, skillPath := sourceRefPath(sk)
+ source = buildInstallSource(source, ref, skillPath)
+ if !safeCLIValue(source) {
+ return "", "", false, "source is empty or option-like"
+ }
+ filter := compat.SanitizeMetadata(sk.Name)
+ if !safeCLIValue(filter) {
+ return "", "", false, "skill name is empty or option-like"
+ }
+ return source, filter, true, ""
+}
+
+func removeIdentity(sk *model.Skill) (target string, ok bool, reason string) {
+ for _, path := range candidateInstallPaths(sk) {
+ base := compat.SanitizeName(filepath.Base(path))
+ if safeCLIValue(base) {
+ return base, true, ""
+ }
+ }
+ fallback := compat.SanitizeName(sk.Name)
+ if safeCLIValue(sk.Name) && safeCLIValue(fallback) {
+ return fallback, true, ""
+ }
+ return "", false, "installed directory identity is empty or option-like"
+}
+
+func sourceRefPath(sk *model.Skill) (source, ref, skillPath string) {
+ if sk.Scope == model.ScopeProject && sk.LocalLock != nil {
+ return sk.LocalLock.Source, sk.LocalLock.Ref, sk.LocalLock.SkillPath
+ }
+ if sk.Scope == model.ScopeGlobal && sk.GlobalLock != nil {
+ return globalUpdateSource(*sk.GlobalLock), sk.GlobalLock.Ref, sk.GlobalLock.SkillPath
+ }
+ if sk.LocalLock != nil {
+ return sk.LocalLock.Source, sk.LocalLock.Ref, sk.LocalLock.SkillPath
+ }
+ if sk.GlobalLock != nil {
+ return globalUpdateSource(*sk.GlobalLock), sk.GlobalLock.Ref, sk.GlobalLock.SkillPath
+ }
+ return "", "", ""
+}
+
+func globalUpdateSource(entry model.GlobalLockEntry) string {
+ if entry.SkillPath == "" {
+ return firstNonEmpty(entry.SourceURL, entry.Source)
+ }
+ return firstNonEmpty(entry.Source, entry.SourceURL)
+}
+
+func buildInstallSource(source, ref, skillPath string) string {
+ source = compat.SanitizeMetadata(source)
+ ref = compat.SanitizeMetadata(ref)
+ skillPath = compat.SanitizeMetadata(skillPath)
+ if source == "" {
+ return ""
+ }
+ if skillPath != "" && supportsAppendedSubpath(source) {
+ folder := deriveSkillFolder(skillPath)
+ if folder != "" {
+ source = strings.TrimRight(source, "/") + "/" + folder
+ }
+ }
+ if ref != "" {
+ source += "#" + ref
+ }
+ return source
+}
+
+func deriveSkillFolder(skillPath string) string {
+ folder := skillPath
+ if strings.HasSuffix(folder, "/SKILL.md") {
+ folder = strings.TrimSuffix(folder, "/SKILL.md")
+ } else if strings.HasSuffix(folder, "SKILL.md") {
+ folder = strings.TrimSuffix(folder, "SKILL.md")
+ }
+ return strings.Trim(folder, "/")
+}
+
+func supportsAppendedSubpath(source string) bool {
+ if strings.HasPrefix(source, "git@") || strings.HasSuffix(source, ".git") {
+ return false
+ }
+ if strings.HasPrefix(source, "https://github.com/") || strings.HasPrefix(source, "https://gitlab.com/") || !strings.Contains(source, "://") {
+ return true
+ }
+ return false
+}
+
+func candidateInstallPaths(sk *model.Skill) []string {
+ paths := []string{}
+ if sk.CanonicalPath != "" {
+ paths = append(paths, sk.CanonicalPath)
+ }
+ for _, observed := range sk.ObservedPaths {
+ if observed.Path != "" {
+ paths = append(paths, observed.Path)
+ }
+ }
+ return paths
+}
+
+func safeCLIValue(value string) bool {
+ value = compat.SanitizeMetadata(value)
+ return value != "" && !strings.HasPrefix(value, "-")
+}
+
+func safeToken(value string) string {
+ value = compat.SanitizeMetadata(value)
+ if value == "" || strings.HasPrefix(value, "-") || strings.ContainsAny(value, " \t\n'\"$`\\!*?[]{}()&;<>|") {
+ return ""
+ }
+ return value
+}
+
+func renderCommand(program string, args []string) string {
+ parts := []string{shellQuote(program)}
+ for _, arg := range args {
+ parts = append(parts, shellQuote(arg))
+ }
+ return strings.Join(parts, " ")
+}
+
+func shellQuote(value string) string {
+ value = compat.SanitizeMetadata(value)
+ if value == "" {
+ return "''"
+ }
+ if strings.ContainsAny(value, " \t\n'\"$`\\!*?[]{}()&;<>|#") {
+ return "'" + strings.ReplaceAll(value, "'", "'\\''") + "'"
+ }
+ return value
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if value != "" {
+ return compat.SanitizeMetadata(value)
+ }
+ }
+ return ""
+}
diff --git a/internal/actions/actions_test.go b/internal/actions/actions_test.go
new file mode 100644
index 0000000..d5e5652
--- /dev/null
+++ b/internal/actions/actions_test.go
@@ -0,0 +1,115 @@
+package actions
+
+import (
+ "strings"
+ "testing"
+
+ "lazyskills/internal/model"
+)
+
+func TestForSkillBuildsStructuredSanitizedCommandPreviews(t *testing.T) {
+ sk := &model.Skill{
+ Name: "Deploy Skill\x1b[31m",
+ Scope: model.ScopeGlobal,
+ CanonicalPath: "/tmp/deploy-skill",
+ GlobalLock: &model.GlobalLockEntry{Source: "owner/repo\x1b[31m", SkillPath: "skills/deploy/SKILL.md", Ref: "v1"},
+ }
+ previews := ForSkill(sk)
+ if len(previews) < 3 {
+ t.Fatalf("expected command previews, got %#v", previews)
+ }
+ for _, preview := range previews {
+ if strings.ContainsRune(preview.Command, '\x1b') {
+ t.Fatalf("command contains escape: %#v", preview)
+ }
+ if preview.Available && preview.Program == "" {
+ t.Fatalf("available preview missing program: %#v", preview)
+ }
+ }
+ add := previewByTitle(t, previews, "Reinstall/update selected skill")
+ if !add.Available || add.Program != "npx" || len(add.Args) == 0 {
+ t.Fatalf("expected structured add preview, got %#v", add)
+ }
+ if !strings.Contains(add.Command, "owner/repo/skills/deploy#v1") {
+ t.Fatalf("expected ref and skill path preserved, got %q", add.Command)
+ }
+}
+
+func TestOptionLookingSkillNameSuppressesMutatingPreviews(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "--all", Scope: model.ScopeProject, LocalLock: &model.LocalLockEntry{Source: "owner/repo"}})
+ add := previewByTitle(t, previews, "Reinstall/update selected skill")
+ remove := previewByTitle(t, previews, "Remove selected skill")
+ if add.Available || remove.Available {
+ t.Fatalf("expected mutating previews unavailable, add=%#v remove=%#v", add, remove)
+ }
+}
+
+func TestOptionLookingSourceSuppressesAddPreview(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "Deploy", Scope: model.ScopeProject, CanonicalPath: "/tmp/deploy", LocalLock: &model.LocalLockEntry{Source: "--all"}})
+ add := previewByTitle(t, previews, "Reinstall/update selected skill")
+ remove := previewByTitle(t, previews, "Remove selected skill")
+ if add.Available {
+ t.Fatalf("expected add preview unavailable for option-like source: %#v", add)
+ }
+ if !remove.Available || !strings.Contains(remove.Command, "deploy") {
+ t.Fatalf("expected safe remove preview from install identity, got %#v", remove)
+ }
+}
+
+func TestRemoveUsesInstallDirectoryIdentityNotDisplayName(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "Display Name", Scope: model.ScopeProject, CanonicalPath: "/tmp/display-name", LocalLock: &model.LocalLockEntry{Source: "owner/repo"}})
+ remove := previewByTitle(t, previews, "Remove selected skill")
+ if !remove.Available {
+ t.Fatalf("expected remove preview available: %#v", remove)
+ }
+ if strings.Contains(remove.Command, "Display Name") || !strings.Contains(remove.Command, "display-name") {
+ t.Fatalf("expected install directory target, got %q", remove.Command)
+ }
+}
+
+func TestGenericGitSourceKeepsRefButDoesNotAppendSkillPath(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "Deploy", Scope: model.ScopeGlobal, CanonicalPath: "/tmp/deploy", GlobalLock: &model.GlobalLockEntry{Source: "[email protected]:owner/repo.git", Ref: "main", SkillPath: "skills/deploy/SKILL.md"}})
+ add := previewByTitle(t, previews, "Reinstall/update selected skill")
+ if !add.Available {
+ t.Fatalf("expected add preview available: %#v", add)
+ }
+ if !strings.Contains(add.Command, "[email protected]:owner/repo.git#main") || strings.Contains(add.Command, "skills/deploy") {
+ t.Fatalf("expected ref without appended subpath, got %q", add.Command)
+ }
+}
+
+func TestGlobalNoSkillPathPrefersSourceURL(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "Deploy", Scope: model.ScopeGlobal, CanonicalPath: "/tmp/deploy", GlobalLock: &model.GlobalLockEntry{Source: "example.com", SourceURL: "https://example.com/.well-known/agent-skills/index.json", Ref: "v1"}})
+ add := previewByTitle(t, previews, "Reinstall/update selected skill")
+ if !add.Available {
+ t.Fatalf("expected add preview available: %#v", add)
+ }
+ if !strings.Contains(add.Command, "https://example.com/.well-known/agent-skills/index.json#v1") {
+ t.Fatalf("expected sourceUrl with ref when skillPath missing, got %q", add.Command)
+ }
+ if strings.Contains(add.Command, "example.com#v1") {
+ t.Fatalf("did not expect source host fallback when sourceUrl exists, got %q", add.Command)
+ }
+}
+
+func TestGlobalWithSkillPathPrefersSourceForSubpath(t *testing.T) {
+ previews := ForSkill(&model.Skill{Name: "Deploy", Scope: model.ScopeGlobal, CanonicalPath: "/tmp/deploy", GlobalLock: &model.GlobalLockEntry{Source: "owner/repo", SourceURL: "https://github.com/owner/repo", Ref: "v1", SkillPath: "skills/deploy/SKILL.md"}})
+ add := previewByTitle(t, previews, "Reinstall/update selected skill")
+ if !add.Available {
+ t.Fatalf("expected add preview available: %#v", add)
+ }
+ if !strings.Contains(add.Command, "owner/repo/skills/deploy#v1") {
+ t.Fatalf("expected source with appended skill folder and ref, got %q", add.Command)
+ }
+}
+
+func previewByTitle(t *testing.T, previews []CommandPreview, title string) CommandPreview {
+ t.Helper()
+ for _, preview := range previews {
+ if preview.Title == title {
+ return preview
+ }
+ }
+ t.Fatalf("preview %q not found in %#v", title, previews)
+ return CommandPreview{}
+}
diff --git a/internal/agents/agents.go b/internal/agents/agents.go
new file mode 100644
index 0000000..693157d
--- /dev/null
+++ b/internal/agents/agents.go
@@ -0,0 +1,76 @@
+package agents
+
+import (
+ "os"
+ "path/filepath"
+
+ "lazyskills/internal/model"
+)
+
+type Agent struct {
+ Name string
+ Display string
+ ProjectDir string
+ GlobalDir string
+ Universal bool
+}
+
+func configHome() string {
+ if v := os.Getenv("XDG_CONFIG_HOME"); v != "" {
+ return v
+ }
+ home, _ := os.UserHomeDir()
+ return filepath.Join(home, ".config")
+}
+
+func homeJoin(parts ...string) string {
+ home, _ := os.UserHomeDir()
+ all := append([]string{home}, parts...)
+ return filepath.Join(all...)
+}
+
+func InitialAgents() []Agent {
+ codexHome := os.Getenv("CODEX_HOME")
+ if codexHome == "" {
+ codexHome = homeJoin(".codex")
+ }
+ claudeHome := os.Getenv("CLAUDE_CONFIG_DIR")
+ if claudeHome == "" {
+ claudeHome = homeJoin(".claude")
+ }
+
+ return []Agent{
+ {Name: "universal", Display: "Universal", ProjectDir: ".agents/skills", GlobalDir: homeJoin(".agents", "skills"), Universal: true},
+ {Name: "opencode", Display: "OpenCode", ProjectDir: ".agents/skills", GlobalDir: filepath.Join(configHome(), "opencode", "skills"), Universal: true},
+ {Name: "claude-code", Display: "Claude Code", ProjectDir: ".claude/skills", GlobalDir: filepath.Join(claudeHome, "skills")},
+ {Name: "cursor", Display: "Cursor", ProjectDir: ".agents/skills", GlobalDir: homeJoin(".cursor", "skills"), Universal: true},
+ {Name: "codex", Display: "Codex", ProjectDir: ".agents/skills", GlobalDir: filepath.Join(codexHome, "skills"), Universal: true},
+ }
+}
+
+type Location struct {
+ Root string
+ Scope model.Scope
+ AgentName string
+ Canonical bool
+}
+
+func Locations(cwd string) []Location {
+ var out []Location
+ globalCanonical := homeJoin(".agents", "skills")
+ for _, a := range InitialAgents() {
+ out = append(out, Location{
+ Root: filepath.Join(cwd, filepath.FromSlash(a.ProjectDir)),
+ Scope: model.ScopeProject,
+ AgentName: a.Name,
+ Canonical: a.ProjectDir == ".agents/skills",
+ })
+ if a.Universal {
+ out = append(out, Location{Root: globalCanonical, Scope: model.ScopeGlobal, AgentName: a.Name, Canonical: true})
+ }
+ if a.GlobalDir != "" && a.GlobalDir != globalCanonical {
+ out = append(out, Location{Root: a.GlobalDir, Scope: model.ScopeGlobal, AgentName: a.Name, Canonical: false})
+ }
+ }
+ return out
+}
diff --git a/internal/compat/compat.go b/internal/compat/compat.go
new file mode 100644
index 0000000..211b72e
--- /dev/null
+++ b/internal/compat/compat.go
@@ -0,0 +1,91 @@
+package compat
+
+import (
+ "regexp"
+ "strings"
+
+ "lazyskills/internal/model"
+)
+
+var unsafeNameChars = regexp.MustCompile(`[^a-z0-9._]+`)
+var trimNameChars = regexp.MustCompile(`^[.\-]+|[.\-]+$`)
+
+// SanitizeName mirrors vercel-labs/skills installer.ts sanitizeName.
+func SanitizeName(name string) string {
+ s := strings.ToLower(name)
+ s = unsafeNameChars.ReplaceAllString(s, "-")
+ s = trimNameChars.ReplaceAllString(s, "")
+ if len(s) > 255 {
+ s = s[:255]
+ }
+ if s == "" {
+ return "unnamed-skill"
+ }
+ return s
+}
+
+func NormalizeName(name string) string {
+ return strings.ToLower(strings.TrimSpace(name))
+}
+
+var csiRE = regexp.MustCompile(`\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]`)
+var oscRE = regexp.MustCompile(`\x1b\][\s\S]*?(?:\x07|\x1b\\)`)
+var dcsPMAPCRE = regexp.MustCompile(`\x1b[P^_][\s\S]*?(?:\x1b\\)`)
+var simpleEscRE = regexp.MustCompile(`\x1b[\x20-\x7e]`)
+var c1RE = regexp.MustCompile(`[\x80-\x9f]`)
+var controlRE = regexp.MustCompile(`[\x00-\x06\x07\x08\x0b\x0c\x0d-\x1b\x1c-\x1f\x7f]`)
+var newlineRE = regexp.MustCompile(`[\r\n]+`)
+
+func StripTerminalEscapes(str string) string {
+ str = oscRE.ReplaceAllString(str, "")
+ str = dcsPMAPCRE.ReplaceAllString(str, "")
+ str = csiRE.ReplaceAllString(str, "")
+ str = simpleEscRE.ReplaceAllString(str, "")
+ str = c1RE.ReplaceAllString(str, "")
+ return controlRE.ReplaceAllString(str, "")
+}
+
+func SanitizeMetadata(str string) string {
+ return strings.TrimSpace(newlineRE.ReplaceAllString(StripTerminalEscapes(str), " "))
+}
+
+// SanitizePreviewContent strips terminal controls while preserving markdown line breaks.
+func SanitizePreviewContent(str string) string {
+ return StripTerminalEscapes(str)
+}
+
+type LocalLockDisplay struct {
+ Source string `json:"source,omitempty"`
+ Ref string `json:"ref,omitempty"`
+ SourceType string `json:"sourceType,omitempty"`
+ SkillPath string `json:"skillPath,omitempty"`
+}
+
+type GlobalLockDisplay struct {
+ Source string `json:"source,omitempty"`
+ SourceType string `json:"sourceType,omitempty"`
+ SourceURL string `json:"sourceUrl,omitempty"`
+ Ref string `json:"ref,omitempty"`
+ SkillPath string `json:"skillPath,omitempty"`
+ PluginName string `json:"pluginName,omitempty"`
+}
+
+func SanitizeLocalLockDisplay(entry model.LocalLockEntry) LocalLockDisplay {
+ return LocalLockDisplay{
+ Source: SanitizeMetadata(entry.Source),
+ Ref: SanitizeMetadata(entry.Ref),
+ SourceType: SanitizeMetadata(entry.SourceType),
+ SkillPath: SanitizeMetadata(entry.SkillPath),
+ }
+}
+
+func SanitizeGlobalLockDisplay(entry model.GlobalLockEntry) GlobalLockDisplay {
+ return GlobalLockDisplay{
+ Source: SanitizeMetadata(entry.Source),
+ SourceType: SanitizeMetadata(entry.SourceType),
+ SourceURL: SanitizeMetadata(entry.SourceURL),
+ Ref: SanitizeMetadata(entry.Ref),
+ SkillPath: SanitizeMetadata(entry.SkillPath),
+ PluginName: SanitizeMetadata(entry.PluginName),
+ }
+}
diff --git a/internal/compat/compat_test.go b/internal/compat/compat_test.go
new file mode 100644
index 0000000..eaf8a85
--- /dev/null
+++ b/internal/compat/compat_test.go
@@ -0,0 +1,53 @@
+package compat
+
+import (
+ "testing"
+
+ "lazyskills/internal/model"
+)
+
+func TestSanitizeLockDisplayKeepsRawSeparate(t *testing.T) {
+ local := model.LocalLockEntry{
+ Source: "owner/\x1b[31mrepo",
+ Ref: "main\nnext",
+ SourceType: "github",
+ SkillPath: "skills/\x1b]0;bad\x07demo/SKILL.md",
+ }
+ display := SanitizeLocalLockDisplay(local)
+ if local.Source != "owner/\x1b[31mrepo" {
+ t.Fatalf("raw local lock was mutated: %#v", local)
+ }
+ if display.Source != "owner/repo" || display.Ref != "main next" || display.SkillPath != "skills/demo/SKILL.md" {
+ t.Fatalf("unexpected sanitized local display: %#v", display)
+ }
+
+ global := model.GlobalLockEntry{
+ Source: "owner/\x1b[31mrepo",
+ SourceURL: "https://example.com/\x1b[31mrepo",
+ Ref: "main\nnext",
+ SkillPath: "skills/demo\r/SKILL.md",
+ PluginName: "plugin\x07name",
+ }
+ gdisplay := SanitizeGlobalLockDisplay(global)
+ if global.SourceURL != "https://example.com/\x1b[31mrepo" {
+ t.Fatalf("raw global lock was mutated: %#v", global)
+ }
+ if gdisplay.Source != "owner/repo" || gdisplay.SourceURL != "https://example.com/repo" || gdisplay.Ref != "main next" || gdisplay.SkillPath != "skills/demo/SKILL.md" || gdisplay.PluginName != "pluginname" {
+ t.Fatalf("unexpected sanitized global display: %#v", gdisplay)
+ }
+}
+
+func TestSanitizePreviewContentPreservesNewlines(t *testing.T) {
+ got := SanitizePreviewContent("# Title\n\x1b[31mRed\x1b[0m\nNext")
+ want := "# Title\nRed\nNext"
+ if got != want {
+ t.Fatalf("got %q, want %q", got, want)
+ }
+}
+
+func TestStripTerminalEscapesRemovesBareEsc(t *testing.T) {
+ got := StripTerminalEscapes("before\x1b")
+ if got != "before" {
+ t.Fatalf("got %q", got)
+ }
+}
diff --git a/internal/display/display.go b/internal/display/display.go
new file mode 100644
index 0000000..84db1bb
--- /dev/null
+++ b/internal/display/display.go
@@ -0,0 +1,100 @@
+package display
+
+import (
+ "fmt"
+ "strings"
+
+ "lazyskills/internal/compat"
+ "lazyskills/internal/model"
+)
+
+type SkillView struct {
+ Name string
+ Description string
+ Scope string
+ CanonicalPath string
+ SkillPath string
+ Observed []ObservedPathView
+ LocalLock *compat.LocalLockDisplay
+ GlobalLock *compat.GlobalLockDisplay
+ HealthIssues []HealthIssueView
+ Preview string
+}
+
+type ObservedPathView struct {
+ Path string
+ Scope string
+ Agent string
+ Status string
+ TargetPath string
+}
+
+type HealthIssueView struct {
+ Type string
+ Severity string
+ Message string
+ Path string
+}
+
+func Skill(sk *model.Skill) SkillView {
+ if sk == nil {
+ return SkillView{}
+ }
+ view := SkillView{
+ Name: compat.SanitizeMetadata(sk.Name),
+ Description: compat.SanitizeMetadata(sk.Description),
+ Scope: compat.SanitizeMetadata(string(sk.Scope)),
+ CanonicalPath: compat.SanitizeMetadata(sk.CanonicalPath),
+ SkillPath: compat.SanitizeMetadata(sk.SkillPath),
+ }
+ for _, p := range sk.ObservedPaths {
+ view.Observed = append(view.Observed, ObservedPathView{
+ Path: compat.SanitizeMetadata(p.Path),
+ Scope: compat.SanitizeMetadata(string(p.Scope)),
+ Agent: compat.SanitizeMetadata(p.Agent),
+ Status: compat.SanitizeMetadata(string(p.Status)),
+ TargetPath: compat.SanitizeMetadata(p.TargetPath),
+ })
+ }
+ if sk.LocalLock != nil {
+ lock := compat.SanitizeLocalLockDisplay(*sk.LocalLock)
+ view.LocalLock = &lock
+ }
+ if sk.GlobalLock != nil {
+ lock := compat.SanitizeGlobalLockDisplay(*sk.GlobalLock)
+ view.GlobalLock = &lock
+ }
+ for _, issue := range sk.HealthIssues {
+ view.HealthIssues = append(view.HealthIssues, HealthIssueView{
+ Type: compat.SanitizeMetadata(issue.Type),
+ Severity: compat.SanitizeMetadata(issue.Severity),
+ Message: compat.SanitizeMetadata(issue.Message),
+ Path: compat.SanitizeMetadata(issue.Path),
+ })
+ }
+ view.Preview = compat.SanitizePreviewContent(sk.Preview)
+ return view
+}
+
+func LockSummary(view SkillView) string {
+ parts := []string{}
+ if view.LocalLock != nil {
+ parts = append(parts, fmt.Sprintf("project: %s", firstNonEmpty(view.LocalLock.Source, view.LocalLock.SkillPath, "tracked")))
+ }
+ if view.GlobalLock != nil {
+ parts = append(parts, fmt.Sprintf("global: %s", firstNonEmpty(view.GlobalLock.Source, view.GlobalLock.SourceURL, view.GlobalLock.SkillPath, "tracked")))
+ }
+ if len(parts) == 0 {
+ return "not tracked"
+ }
+ return strings.Join(parts, " | ")
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if value != "" {
+ return value
+ }
+ }
+ return ""
+}
diff --git a/internal/display/display_test.go b/internal/display/display_test.go
new file mode 100644
index 0000000..1f0cc9e
--- /dev/null
+++ b/internal/display/display_test.go
@@ -0,0 +1,54 @@
+package display
+
+import (
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "lazyskills/internal/model"
+)
+
+func TestSkillViewSanitizesRenderedFields(t *testing.T) {
+ sk := &model.Skill{
+ Name: "Bad\x1b[31m Name",
+ Description: "Line one\nLine two",
+ Scope: model.ScopeProject,
+ SkillPath: filepath.Join(t.TempDir(), "SKILL.md"),
+ Preview: "# Hi\n\x1b[31mred",
+ ObservedPaths: []model.ObservedPath{{
+ Path: "/tmp/\x1b[31mskill",
+ Scope: model.ScopeProject,
+ Agent: "opencode\x07",
+ Status: model.StatusCanonical,
+ }},
+ LocalLock: &model.LocalLockEntry{Source: "owner/\x1b[31mrepo", SkillPath: "skills/demo\r/SKILL.md"},
+ HealthIssues: []model.HealthIssue{{
+ Type: "broken_symlink",
+ Message: "bad\x1b[31m message",
+ Path: "/tmp/bad\x07",
+ }},
+ }
+ view := Skill(sk)
+ if strings.Contains(view.Name, "\x1b") || strings.Contains(view.Observed[0].Path, "\x1b") || strings.Contains(view.HealthIssues[0].Message, "\x1b") {
+ t.Fatalf("expected sanitized view: %#v", view)
+ }
+ if view.Name != "Bad Name" || view.Description != "Line one Line two" || view.LocalLock.Source != "owner/repo" {
+ t.Fatalf("unexpected sanitized fields: %#v", view)
+ }
+ if view.Preview != "# Hi\nred" {
+ t.Fatalf("unexpected preview %q", view.Preview)
+ }
+}
+
+func TestSkillViewDoesNotReadPreviewFromFilesystem(t *testing.T) {
+ dir := t.TempDir()
+ skillPath := filepath.Join(dir, "SKILL.md")
+ if err := os.WriteFile(skillPath, []byte("# filesystem content"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ view := Skill(&model.Skill{Name: "Preview", Description: "desc", Scope: model.ScopeProject, SkillPath: skillPath})
+ if view.Preview != "" {
+ t.Fatalf("display.Skill should not read preview during render, got %q", view.Preview)
+ }
+}
diff --git a/internal/frontmatter/frontmatter.go b/internal/frontmatter/frontmatter.go
new file mode 100644
index 0000000..46fe31e
--- /dev/null
+++ b/internal/frontmatter/frontmatter.go
@@ -0,0 +1,56 @@
+package frontmatter
+
+import (
+ "errors"
+ "os"
+ "regexp"
+
+ "lazyskills/internal/compat"
+
+ "gopkg.in/yaml.v3"
+)
+
+var frontmatterRE = regexp.MustCompile(`(?s)^---\r?\n(.*?)\r?\n---\r?\n?(.*)$`)
+
+type SkillDoc struct {
+ Name string
+ Description string
+ Content string
+ Raw string
+}
+
+func ParseFile(path string) (SkillDoc, error) {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return SkillDoc{}, err
+ }
+ return Parse(string(b))
+}
+
+func Parse(raw string) (SkillDoc, error) {
+ match := frontmatterRE.FindStringSubmatch(raw)
+ if match == nil {
+ return SkillDoc{Raw: raw, Content: raw}, errors.New("missing YAML frontmatter")
+ }
+
+ var data map[string]any
+ if err := yaml.Unmarshal([]byte(match[1]), &data); err != nil {
+ return SkillDoc{Raw: raw, Content: match[2]}, err
+ }
+
+ name, ok := data["name"].(string)
+ if !ok || name == "" {
+ return SkillDoc{Raw: raw, Content: match[2]}, errors.New("frontmatter name must be a string")
+ }
+ desc, ok := data["description"].(string)
+ if !ok || desc == "" {
+ return SkillDoc{Raw: raw, Content: match[2]}, errors.New("frontmatter description must be a string")
+ }
+
+ name = compat.SanitizeMetadata(name)
+ desc = compat.SanitizeMetadata(desc)
+ if name == "" || desc == "" {
+ return SkillDoc{Raw: raw, Content: match[2]}, errors.New("frontmatter name and description must be non-empty after sanitization")
+ }
+ return SkillDoc{Name: name, Description: desc, Content: match[2], Raw: raw}, nil
+}
diff --git a/internal/locks/locks.go b/internal/locks/locks.go
new file mode 100644
index 0000000..6e6f752
--- /dev/null
+++ b/internal/locks/locks.go
@@ -0,0 +1,51 @@
+package locks
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+
+ "lazyskills/internal/model"
+)
+
+func ProjectLockPath(cwd string) string {
+ return filepath.Join(cwd, "skills-lock.json")
+}
+
+func GlobalLockPath() string {
+ if v := os.Getenv("XDG_STATE_HOME"); v != "" {
+ return filepath.Join(v, "skills", ".skill-lock.json")
+ }
+ home, _ := os.UserHomeDir()
+ return filepath.Join(home, ".agents", ".skill-lock.json")
+}
+
+func ReadLocal(path string) (model.LocalLockFile, error) {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return model.LocalLockFile{Version: 1, Skills: map[string]model.LocalLockEntry{}}, err
+ }
+ var lock model.LocalLockFile
+ if err := json.Unmarshal(b, &lock); err != nil || lock.Version < 1 || lock.Skills == nil {
+ if err == nil {
+ err = os.ErrInvalid
+ }
+ return model.LocalLockFile{Version: 1, Skills: map[string]model.LocalLockEntry{}}, err
+ }
+ return lock, nil
+}
+
+func ReadGlobal(path string) (model.GlobalLockFile, error) {
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return model.GlobalLockFile{Version: 3, Skills: map[string]model.GlobalLockEntry{}}, err
+ }
+ var lock model.GlobalLockFile
+ if err := json.Unmarshal(b, &lock); err != nil || lock.Version < 3 || lock.Skills == nil {
+ if err == nil {
+ err = os.ErrInvalid
+ }
+ return model.GlobalLockFile{Version: 3, Skills: map[string]model.GlobalLockEntry{}}, err
+ }
+ return lock, nil
+}
diff --git a/internal/model/model.go b/internal/model/model.go
new file mode 100644
index 0000000..33a73ba
--- /dev/null
+++ b/internal/model/model.go
@@ -0,0 +1,103 @@
+package model
+
+// Scope represents project-local or machine-global scope.
+type Scope string
+
+const (
+ ScopeProject Scope = "project"
+ ScopeGlobal Scope = "global"
+)
+
+// Status represents the relationship of a path to the skill (canonical repository vs link/copy).
+type Status string
+
+const (
+ StatusCanonical Status = "canonical"
+ StatusSymlink Status = "symlink"
+ StatusCopy Status = "copy"
+ StatusBrokenSymlink Status = "broken_symlink"
+)
+
+// ObservedPath represents one location on disk where this skill was found.
+type ObservedPath struct {
+ Path string `json:"path"`
+ Scope Scope `json:"scope"`
+ Agent string `json:"agent"`
+ Status Status `json:"status"`
+ TargetPath string `json:"target_path,omitempty"` // For symlinks, what they point to
+}
+
+// HealthIssue represents a configuration or discovery issue with a skill.
+type HealthIssue struct {
+ Type string `json:"type"` // e.g. "invalid_frontmatter", "broken_symlink", "duplicate_name"
+ Severity string `json:"severity"` // "error" or "warning"
+ Message string `json:"message"`
+ Path string `json:"path,omitempty"`
+}
+
+// AddHealthIssue appends a health issue unless an identical issue already exists.
+func (sk *Skill) AddHealthIssue(issue HealthIssue) {
+ for _, existing := range sk.HealthIssues {
+ if existing.Type == issue.Type && existing.Severity == issue.Severity && existing.Message == issue.Message && existing.Path == issue.Path {
+ return
+ }
+ }
+ sk.HealthIssues = append(sk.HealthIssues, issue)
+}
+
+// LocalLockEntry is the lock entry in project-local skills-lock.json
+type LocalLockEntry struct {
+ Source string `json:"source"`
+ Ref string `json:"ref,omitempty"`
+ SourceType string `json:"sourceType"`
+ SkillPath string `json:"skillPath,omitempty"`
+ ComputedHash string `json:"computedHash"`
+}
+
+// LocalLockFile represents project-local skills-lock.json
+type LocalLockFile struct {
+ Version int `json:"version"`
+ Skills map[string]LocalLockEntry `json:"skills"`
+}
+
+// GlobalLockEntry is the lock entry in global .skill-lock.json
+type GlobalLockEntry struct {
+ Source string `json:"source"`
+ SourceType string `json:"sourceType"`
+ SourceURL string `json:"sourceUrl"`
+ Ref string `json:"ref,omitempty"`
+ SkillPath string `json:"skillPath,omitempty"`
+ SkillFolderHash string `json:"skillFolderHash"`
+ InstalledAt string `json:"installedAt"`
+ UpdatedAt string `json:"updatedAt"`
+ PluginName string `json:"pluginName,omitempty"`
+}
+
+// GlobalLockFile represents global .skill-lock.json
+type GlobalLockFile struct {
+ Version int `json:"version"`
+ Skills map[string]GlobalLockEntry `json:"skills"`
+}
+
+// Skill represents the consolidated view of a skill.
+type Skill struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Scope Scope `json:"scope"`
+ CanonicalPath string `json:"canonical_path,omitempty"`
+ SkillPath string `json:"skill_path,omitempty"`
+ Preview string `json:"-"`
+ ObservedPaths []ObservedPath `json:"observed_paths"`
+ LocalLock *LocalLockEntry `json:"local_lock,omitempty"`
+ GlobalLock *GlobalLockEntry `json:"global_lock,omitempty"`
+ HealthIssues []HealthIssue `json:"health_issues"`
+}
+
+// ScanResult is the root schema produced by lazyskills scan --json.
+type ScanResult struct {
+ Cwd string `json:"cwd"`
+ GlobalLock string `json:"global_lock_path,omitempty"`
+ ProjectLock string `json:"project_lock_path,omitempty"`
+ Skills []*Skill `json:"skills"`
+ HealthIssues []HealthIssue `json:"health_issues,omitempty"`
+}
diff --git a/internal/scan/scan.go b/internal/scan/scan.go
new file mode 100644
index 0000000..620309e
--- /dev/null
+++ b/internal/scan/scan.go
@@ -0,0 +1,280 @@
+package scan
+
+import (
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+
+ "lazyskills/internal/agents"
+ "lazyskills/internal/compat"
+ "lazyskills/internal/frontmatter"
+ "lazyskills/internal/locks"
+ "lazyskills/internal/model"
+)
+
+func Run(cwd string) (model.ScanResult, error) {
+ absCwd, err := filepath.Abs(cwd)
+ if err != nil {
+ return model.ScanResult{}, err
+ }
+ if st, err := os.Stat(absCwd); err != nil {
+ return model.ScanResult{}, err
+ } else if !st.IsDir() {
+ return model.ScanResult{}, fmt.Errorf("cwd is not a directory: %s", absCwd)
+ }
+
+ res := model.ScanResult{Cwd: absCwd, ProjectLock: locks.ProjectLockPath(absCwd), GlobalLock: locks.GlobalLockPath()}
+ skills := map[string]*model.Skill{}
+
+ localLock, err := locks.ReadLocal(res.ProjectLock)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ res.HealthIssues = append(res.HealthIssues, model.HealthIssue{Type: "corrupt_project_lock", Severity: "warning", Message: err.Error(), Path: res.ProjectLock})
+ }
+ globalLock, err := locks.ReadGlobal(res.GlobalLock)
+ if err != nil && !errors.Is(err, os.ErrNotExist) {
+ res.HealthIssues = append(res.HealthIssues, model.HealthIssue{Type: "corrupt_global_lock", Severity: "warning", Message: err.Error(), Path: res.GlobalLock})
+ }
+
+ for _, loc := range agents.Locations(absCwd) {
+ scanLocation(loc, skills)
+ }
+
+ correlateLocks(skills, localLock.Skills, globalLock.Skills)
+ for key, entry := range localLock.Skills {
+ if !hasLockMatch(skills, model.ScopeProject, key) {
+ sk := ensureSkill(skills, model.ScopeProject, key, key, "")
+ e := entry
+ sk.LocalLock = &e
+ sk.AddHealthIssue(model.HealthIssue{Type: "lock_without_files", Severity: "warning", Message: "project lock entry has no matching skill on disk"})
+ }
+ }
+ for key, entry := range globalLock.Skills {
+ if !hasLockMatch(skills, model.ScopeGlobal, key) {
+ sk := ensureSkill(skills, model.ScopeGlobal, key, key, "")
+ e := entry
+ sk.GlobalLock = &e
+ sk.AddHealthIssue(model.HealthIssue{Type: "lock_without_files", Severity: "warning", Message: "global lock entry has no matching skill on disk"})
+ }
+ }
+
+ addDuplicateAndShadowingIssues(skills)
+ for _, sk := range skills {
+ if len(sk.ObservedPaths) > 0 {
+ if sk.Scope == model.ScopeProject && sk.LocalLock == nil {
+ sk.AddHealthIssue(model.HealthIssue{Type: "missing_project_lock", Severity: "warning", Message: "project skill is present on disk but not found in project lock"})
+ }
+ if sk.Scope == model.ScopeGlobal && sk.GlobalLock == nil {
+ sk.AddHealthIssue(model.HealthIssue{Type: "missing_global_lock", Severity: "warning", Message: "global skill is present on disk but not found in global lock"})
+ }
+ }
+ res.Skills = append(res.Skills, sk)
+ }
+ sort.Slice(res.Skills, func(i, j int) bool {
+ left, right := strings.ToLower(res.Skills[i].Name), strings.ToLower(res.Skills[j].Name)
+ if left == right {
+ return res.Skills[i].Scope < res.Skills[j].Scope
+ }
+ return left < right
+ })
+ return res, nil
+}
+
+func scanLocation(loc agents.Location, skills map[string]*model.Skill) {
+ entries, err := os.ReadDir(loc.Root)
+ if err != nil {
+ return
+ }
+ for _, entry := range entries {
+ path := filepath.Join(loc.Root, entry.Name())
+ info, err := os.Lstat(path)
+ if err != nil {
+ continue
+ }
+ status := model.StatusCopy
+ if loc.Canonical {
+ status = model.StatusCanonical
+ }
+ observed := model.ObservedPath{Path: path, Scope: loc.Scope, Agent: loc.AgentName, Status: status}
+ parseDir := path
+ if info.Mode()&os.ModeSymlink != 0 {
+ target, _ := os.Readlink(path)
+ if !filepath.IsAbs(target) {
+ target = filepath.Join(filepath.Dir(path), target)
+ }
+ observed.TargetPath = filepath.Clean(target)
+ if st, err := os.Stat(path); err != nil || !st.IsDir() {
+ observed.Status = model.StatusBrokenSymlink
+ sk := ensureSkill(skills, loc.Scope, entry.Name(), entry.Name(), "")
+ addObservedPath(sk, observed)
+ sk.AddHealthIssue(model.HealthIssue{Type: "broken_symlink", Severity: "error", Message: "skill path is a broken symlink", Path: path})
+ continue
+ }
+ observed.Status = model.StatusSymlink
+ parseDir = path
+ } else if !info.IsDir() {
+ continue
+ }
+
+ skillFile := filepath.Join(parseDir, "SKILL.md")
+ doc, err := frontmatter.ParseFile(skillFile)
+ if err != nil {
+ sk := ensureSkill(skills, loc.Scope, entry.Name(), entry.Name(), "")
+ addObservedPath(sk, observed)
+ issueType := "invalid_frontmatter"
+ if errors.Is(err, os.ErrNotExist) {
+ issueType = "missing_skill_md"
+ }
+ sk.AddHealthIssue(model.HealthIssue{Type: issueType, Severity: "error", Message: fmt.Sprintf("invalid SKILL.md: %v", err), Path: skillFile})
+ continue
+ }
+
+ sk := ensureSkill(skills, loc.Scope, entry.Name(), doc.Name, doc.Description)
+ if loc.Canonical && sk.CanonicalPath == "" {
+ sk.CanonicalPath = path
+ }
+ if sk.SkillPath == "" {
+ sk.SkillPath = skillFile
+ }
+ if sk.Preview == "" {
+ sk.Preview = doc.Raw
+ }
+ addObservedPath(sk, observed)
+ }
+}
+
+func ensureSkill(skills map[string]*model.Skill, scope model.Scope, keyHint, name, desc string) *model.Skill {
+ keyName := name
+ if compat.NormalizeName(keyName) == "" {
+ keyName = keyHint
+ }
+ key := skillKey(scope, keyName)
+ if sk, ok := skills[key]; ok {
+ if sk.Description == "" && desc != "" {
+ sk.Description = desc
+ }
+ return sk
+ }
+ sk := &model.Skill{Name: keyName, Description: desc, Scope: scope}
+ skills[key] = sk
+ return sk
+}
+
+func skillKey(scope model.Scope, name string) string {
+ return string(scope) + "\x00" + compat.NormalizeName(name)
+}
+
+func addObservedPath(sk *model.Skill, observed model.ObservedPath) {
+ for _, existing := range sk.ObservedPaths {
+ if existing.Path == observed.Path && existing.Agent == observed.Agent && existing.Scope == observed.Scope {
+ return
+ }
+ }
+ sk.ObservedPaths = append(sk.ObservedPaths, observed)
+}
+
+func correlateLocks(skills map[string]*model.Skill, local map[string]model.LocalLockEntry, global map[string]model.GlobalLockEntry) {
+ for _, sk := range skills {
+ if sk.Scope == model.ScopeProject {
+ if e, ok := findLocalLock(local, sk); ok {
+ entry := e
+ sk.LocalLock = &entry
+ }
+ }
+ if sk.Scope == model.ScopeGlobal {
+ if e, ok := findGlobalLock(global, sk); ok {
+ entry := e
+ sk.GlobalLock = &entry
+ }
+ }
+ }
+}
+
+func candidateLockKeys(sk *model.Skill) []string {
+ keys := []string{sk.Name, compat.SanitizeName(sk.Name)}
+ for _, p := range sk.ObservedPaths {
+ base := filepath.Base(p.Path)
+ keys = append(keys, base, compat.SanitizeName(base))
+ }
+ return keys
+}
+
+func findLocalLock(lock map[string]model.LocalLockEntry, sk *model.Skill) (model.LocalLockEntry, bool) {
+ for key, entry := range lock {
+ if lockKeyMatches(key, sk) {
+ return entry, true
+ }
+ }
+ return model.LocalLockEntry{}, false
+}
+
+func findGlobalLock(lock map[string]model.GlobalLockEntry, sk *model.Skill) (model.GlobalLockEntry, bool) {
+ for key, entry := range lock {
+ if lockKeyMatches(key, sk) {
+ return entry, true
+ }
+ }
+ return model.GlobalLockEntry{}, false
+}
+
+func lockKeyMatches(key string, sk *model.Skill) bool {
+ for _, candidate := range candidateLockKeys(sk) {
+ if key == candidate || key == compat.SanitizeName(candidate) || compat.NormalizeName(key) == compat.NormalizeName(candidate) {
+ return true
+ }
+ }
+ return false
+}
+
+func hasLockMatch(skills map[string]*model.Skill, scope model.Scope, key string) bool {
+ for _, sk := range skills {
+ if sk.Scope == scope && lockKeyMatches(key, sk) {
+ return true
+ }
+ }
+ return false
+}
+
+func addDuplicateAndShadowingIssues(skills map[string]*model.Skill) {
+ byName := map[string][]*model.Skill{}
+ for _, sk := range skills {
+ byName[compat.NormalizeName(sk.Name)] = append(byName[compat.NormalizeName(sk.Name)], sk)
+ }
+ for _, group := range byName {
+ if len(group) < 2 {
+ continue
+ }
+ sawProject, sawGlobal := false, false
+ for _, sk := range group {
+ sawProject = sawProject || sk.Scope == model.ScopeProject
+ sawGlobal = sawGlobal || sk.Scope == model.ScopeGlobal
+ }
+ issueType := "duplicate_name"
+ message := "multiple skills share this name"
+ if sawProject && sawGlobal {
+ issueType = "project_global_shadowing"
+ message = "project and global skills share this name"
+ }
+ for _, sk := range group {
+ sk.AddHealthIssue(model.HealthIssue{Type: issueType, Severity: "warning", Message: message})
+ }
+ }
+}
+
+type Scanner struct {
+ Cwd string
+}
+
+func New(cwd string) Scanner {
+ return Scanner{Cwd: cwd}
+}
+
+func (s Scanner) Snapshot() (model.ScanResult, error) {
+ return Run(s.Cwd)
+}
+
+func Snapshot(cwd string) (model.ScanResult, error) {
+ return New(cwd).Snapshot()
+}
diff --git a/internal/scan/scan_test.go b/internal/scan/scan_test.go
new file mode 100644
index 0000000..87a0ea6
--- /dev/null
+++ b/internal/scan/scan_test.go
@@ -0,0 +1,357 @@
+package scan
+
+import (
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func writeSkill(t *testing.T, dir, name, desc string) {
+ t.Helper()
+ if err := os.MkdirAll(dir, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ content := "---\nname: " + name + "\ndescription: " + desc + "\n---\n\n# " + name + "\n"
+ if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func withHome(t *testing.T) string {
+ t.Helper()
+ home := t.TempDir()
+ t.Setenv("HOME", home)
+ t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
+ t.Setenv("XDG_STATE_HOME", filepath.Join(home, ".local", "state"))
+ t.Setenv("CLAUDE_CONFIG_DIR", filepath.Join(home, ".claude"))
+ t.Setenv("CODEX_HOME", filepath.Join(home, ".codex"))
+ return home
+}
+
+func findSkill(t *testing.T, skills any, name string) map[string]any {
+ t.Helper()
+ list := skills.([]any)
+ for _, item := range list {
+ m := item.(map[string]any)
+ if m["name"] == name {
+ return m
+ }
+ }
+ t.Fatalf("skill %q not found", name)
+ return nil
+}
+
+func TestUniversalProjectVisibilityForUniversalAgents(t *testing.T) {
+ withHome(t)
+ cwd := t.TempDir()
+ writeSkill(t, filepath.Join(cwd, ".agents", "skills", "build"), "Build Tools", "Use build tools")
+
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Skills) != 1 {
+ t.Fatalf("expected 1 skill, got %d", len(res.Skills))
+ }
+ seen := map[string]bool{}
+ for _, p := range res.Skills[0].ObservedPaths {
+ seen[p.Agent] = true
+ }
+ for _, agent := range []string{"universal", "opencode", "cursor", "codex"} {
+ if !seen[agent] {
+ t.Fatalf("expected %s to observe .agents/skills", agent)
+ }
+ }
+ if seen["claude-code"] {
+ t.Fatalf("claude-code should not observe project .agents/skills")
+ }
+}
+
+func TestClaudeProjectDir(t *testing.T) {
+ withHome(t)
+ cwd := t.TempDir()
+ writeSkill(t, filepath.Join(cwd, ".claude", "skills", "review"), "Review", "Review code")
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Skills) != 1 {
+ t.Fatalf("expected 1 skill, got %d", len(res.Skills))
+ }
+ if got := res.Skills[0].ObservedPaths[0].Agent; got != "claude-code" {
+ t.Fatalf("expected claude-code observation, got %s", got)
+ }
+}
+
+func TestLocksCorrelateBySkillName(t *testing.T) {
+ home := withHome(t)
+ cwd := t.TempDir()
+ writeSkill(t, filepath.Join(cwd, ".agents", "skills", "pretty-name"), "Pretty Name", "Pretty desc")
+ writeSkill(t, filepath.Join(home, ".agents", "skills", "pretty-name"), "Pretty Name", "Pretty desc")
+ localLock := `{"version":1,"skills":{"Pretty Name":{"source":"owner/repo","sourceType":"github","computedHash":"abc"}}}`
+ if err := os.WriteFile(filepath.Join(cwd, "skills-lock.json"), []byte(localLock), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ globalLockPath := filepath.Join(home, ".local", "state", "skills", ".skill-lock.json")
+ if err := os.MkdirAll(filepath.Dir(globalLockPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ globalLock := `{"version":3,"skills":{"pretty-name":{"source":"owner/repo","sourceType":"github","sourceUrl":"https://github.com/owner/repo","skillFolderHash":"def","installedAt":"now","updatedAt":"now"}}}`
+ if err := os.WriteFile(globalLockPath, []byte(globalLock), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var sawLocal, sawGlobal bool
+ for _, sk := range res.Skills {
+ if sk.Scope == "project" && sk.LocalLock != nil {
+ sawLocal = true
+ }
+ if sk.Scope == "global" && sk.GlobalLock != nil {
+ sawGlobal = true
+ }
+ }
+ if !sawLocal || !sawGlobal {
+ t.Fatalf("expected scoped locks correlated, local=%v global=%v skills=%#v", sawLocal, sawGlobal, res.Skills)
+ }
+}
+
+func TestGlobalCanonicalVisibleToUniversalAgents(t *testing.T) {
+ home := withHome(t)
+ cwd := t.TempDir()
+ writeSkill(t, filepath.Join(home, ".agents", "skills", "global-build"), "Global Build", "Global build desc")
+
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Skills) != 1 {
+ t.Fatalf("expected 1 skill, got %d", len(res.Skills))
+ }
+ seen := map[string]bool{}
+ for _, p := range res.Skills[0].ObservedPaths {
+ if p.Scope == "global" && p.Status == "canonical" {
+ seen[p.Agent] = true
+ }
+ }
+ for _, agent := range []string{"universal", "opencode", "cursor", "codex"} {
+ if !seen[agent] {
+ t.Fatalf("expected %s to observe global canonical .agents/skills", agent)
+ }
+ }
+}
+
+func TestProjectAndGlobalSameNameAreSeparateWithShadowing(t *testing.T) {
+ home := withHome(t)
+ cwd := t.TempDir()
+ writeSkill(t, filepath.Join(cwd, ".agents", "skills", "same"), "Same", "Project desc")
+ writeSkill(t, filepath.Join(home, ".agents", "skills", "same"), "Same", "Global desc")
+
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Skills) != 2 {
+ t.Fatalf("expected separate project/global skills, got %d", len(res.Skills))
+ }
+ for _, sk := range res.Skills {
+ var shadow bool
+ for _, issue := range sk.HealthIssues {
+ if issue.Type == "project_global_shadowing" {
+ shadow = true
+ }
+ }
+ if !shadow {
+ t.Fatalf("expected shadowing issue on %#v", sk)
+ }
+ }
+}
+
+func TestScopeSpecificMissingLocks(t *testing.T) {
+ home := withHome(t)
+ cwd := t.TempDir()
+ writeSkill(t, filepath.Join(cwd, ".agents", "skills", "locked-global-only"), "Locked Global Only", "Project desc")
+ globalLockPath := filepath.Join(home, ".local", "state", "skills", ".skill-lock.json")
+ if err := os.MkdirAll(filepath.Dir(globalLockPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ globalLock := `{"version":3,"skills":{"Locked Global Only":{"source":"owner/repo","sourceType":"github","sourceUrl":"https://github.com/owner/repo","skillFolderHash":"def","installedAt":"now","updatedAt":"now"}}}`
+ if err := os.WriteFile(globalLockPath, []byte(globalLock), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Skills) != 2 {
+ t.Fatalf("expected project skill plus global lock-without-files, got %d", len(res.Skills))
+ }
+ var missingProject, lockWithoutFiles bool
+ for _, sk := range res.Skills {
+ for _, issue := range sk.HealthIssues {
+ missingProject = missingProject || issue.Type == "missing_project_lock"
+ lockWithoutFiles = lockWithoutFiles || issue.Type == "lock_without_files"
+ }
+ }
+ if !missingProject || !lockWithoutFiles {
+ t.Fatalf("expected missing project lock and global lock_without_files, got %#v", res.Skills)
+ }
+}
+
+func TestMissingSkillMDAndMetadataSanitization(t *testing.T) {
+ withHome(t)
+ cwd := t.TempDir()
+ root := filepath.Join(cwd, ".agents", "skills")
+ if err := os.MkdirAll(filepath.Join(root, "missing-md"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ esc := filepath.Join(root, "escape")
+ if err := os.MkdirAll(esc, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ content := "---\nname: \"Bad\\u001b[31m Name\"\ndescription: \"Line one\\nLine two\"\n---\nbody"
+ if err := os.WriteFile(filepath.Join(esc, "SKILL.md"), []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var missing, sanitized bool
+ for _, sk := range res.Skills {
+ for _, issue := range sk.HealthIssues {
+ missing = missing || issue.Type == "missing_skill_md"
+ }
+ if sk.Name == "Bad Name" && sk.Description == "Line one Line two" {
+ sanitized = true
+ }
+ }
+ if !missing || !sanitized {
+ t.Fatalf("expected missing_skill_md and sanitized metadata, missing=%v sanitized=%v skills=%#v", missing, sanitized, res.Skills)
+ }
+}
+
+func TestBrokenSymlinkAndInvalidFrontmatter(t *testing.T) {
+ withHome(t)
+ cwd := t.TempDir()
+ root := filepath.Join(cwd, ".agents", "skills")
+ if err := os.MkdirAll(root, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(filepath.Join(cwd, "missing"), filepath.Join(root, "broken")); err != nil {
+ t.Fatal(err)
+ }
+ bad := filepath.Join(root, "bad")
+ if err := os.MkdirAll(bad, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(bad, "SKILL.md"), []byte("---\nname: 123\n---\nbody"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var broken, invalid bool
+ for _, sk := range res.Skills {
+ for _, issue := range sk.HealthIssues {
+ if issue.Type == "broken_symlink" {
+ broken = true
+ }
+ if issue.Type == "invalid_frontmatter" {
+ invalid = true
+ }
+ }
+ }
+ if !broken || !invalid {
+ t.Fatalf("expected broken and invalid issues, broken=%v invalid=%v", broken, invalid)
+ }
+}
+
+func TestSharedUniversalHealthIssuesAreDeduplicated(t *testing.T) {
+ withHome(t)
+ cwd := t.TempDir()
+ root := filepath.Join(cwd, ".agents", "skills")
+ if err := os.MkdirAll(filepath.Join(root, "missing-md"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Skills) != 1 {
+ t.Fatalf("expected 1 skill, got %d", len(res.Skills))
+ }
+ var missingCount int
+ for _, issue := range res.Skills[0].HealthIssues {
+ if issue.Type == "missing_skill_md" {
+ missingCount++
+ }
+ }
+ if missingCount != 1 {
+ t.Fatalf("expected exactly one missing_skill_md issue, got %d issues=%#v", missingCount, res.Skills[0].HealthIssues)
+ }
+ if len(res.Skills[0].ObservedPaths) != 4 {
+ t.Fatalf("expected observed paths for universal/opencode/cursor/codex, got %#v", res.Skills[0].ObservedPaths)
+ }
+}
+
+func TestSnapshotBoundary(t *testing.T) {
+ withHome(t)
+ cwd := t.TempDir()
+ writeSkill(t, filepath.Join(cwd, ".agents", "skills", "build"), "Build", "Build desc")
+
+ res, err := Snapshot(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Skills) != 1 || res.Skills[0].Name != "Build" {
+ t.Fatalf("unexpected snapshot result: %#v", res.Skills)
+ }
+
+ scanner := New(cwd)
+ res, err = scanner.Snapshot()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Skills) != 1 || res.Skills[0].Name != "Build" {
+ t.Fatalf("unexpected scanner snapshot result: %#v", res.Skills)
+ }
+}
+
+func TestSnapshotLoadsPreviewOnce(t *testing.T) {
+ withHome(t)
+ cwd := t.TempDir()
+ writeSkill(t, filepath.Join(cwd, ".agents", "skills", "preview"), "Preview", "Preview desc")
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.Skills) != 1 || res.Skills[0].Preview == "" {
+ t.Fatalf("expected scanner snapshot to load preview, got %#v", res.Skills)
+ }
+}
+
+func TestCorruptLockProducesTopLevelWarningAndJSONEncodes(t *testing.T) {
+ withHome(t)
+ cwd := t.TempDir()
+ if err := os.WriteFile(filepath.Join(cwd, "skills-lock.json"), []byte("{not json"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ res, err := Run(cwd)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(res.HealthIssues) == 0 || res.HealthIssues[0].Type != "corrupt_project_lock" {
+ t.Fatalf("expected corrupt_project_lock issue, got %#v", res.HealthIssues)
+ }
+ if _, err := json.Marshal(res); err != nil {
+ t.Fatalf("result should JSON encode: %v", err)
+ }
+}
diff --git a/internal/tui/tui.go b/internal/tui/tui.go
new file mode 100644
index 0000000..bc3219e
--- /dev/null
+++ b/internal/tui/tui.go
@@ -0,0 +1,581 @@
+package tui
+
+import (
+ "fmt"
+ "sort"
+ "strings"
+
+ "github.com/charmbracelet/bubbles/viewport"
+ tea "github.com/charmbracelet/bubbletea"
+ "github.com/charmbracelet/lipgloss"
+ "github.com/muesli/reflow/wordwrap"
+
+ "lazyskills/internal/actions"
+ "lazyskills/internal/agents"
+ "lazyskills/internal/compat"
+ "lazyskills/internal/display"
+ "lazyskills/internal/model"
+ "lazyskills/internal/scan"
+)
+
+type scopeFilter int
+
+const (
+ scopeAll scopeFilter = iota
+ scopeProject
+ scopeGlobal
+)
+
+type appModel struct {
+ cwd string
+ result model.ScanResult
+ err error
+ selected int
+ filter scopeFilter
+ agent string
+ search string
+ searching bool
+ commands bool
+ help bool
+ width int
+ height int
+ viewport viewport.Model
+}
+
+var (
+ titleStyle = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("212"))
+ borderStyle = lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).Padding(0, 1)
+ selectedStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("230")).Background(lipgloss.Color("62"))
+ dimStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("241"))
+ errorStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("203"))
+)
+
+type snapshotMsg struct {
+ result model.ScanResult
+ err error
+}
+
+func Run(cwd string) error {
+ program := tea.NewProgram(newModel(cwd), tea.WithAltScreen())
+ _, err := program.Run()
+ return err
+}
+
+func newModel(cwd string) appModel {
+ return appModel{cwd: cwd, help: true, viewport: viewport.New(0, 0)}
+}
+
+func (m appModel) Init() tea.Cmd {
+ return loadSnapshot(m.cwd)
+}
+
+func loadSnapshot(cwd string) tea.Cmd {
+ return func() tea.Msg {
+ result, err := scan.Snapshot(cwd)
+ return snapshotMsg{result: result, err: err}
+ }
+}
+
+func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
+ switch msg := msg.(type) {
+ case tea.WindowSizeMsg:
+ m.width = msg.Width
+ m.height = msg.Height
+ m.syncViewport()
+ case snapshotMsg:
+ m.result = msg.result
+ m.err = msg.err
+ m.clampSelection()
+ m.syncViewport()
+ case tea.KeyMsg:
+ key := msg.String()
+ if m.searching {
+ switch key {
+ case "esc", "enter":
+ m.searching = false
+ case "backspace", "ctrl+h":
+ if len(m.search) > 0 {
+ m.search = m.search[:len(m.search)-1]
+ m.selected = 0
+ }
+ default:
+ if len(key) == 1 {
+ m.search += key
+ m.selected = 0
+ }
+ }
+ m.clampSelection()
+ m.syncViewport()
+ return m, nil
+ }
+
+ switch key {
+ case "q", "ctrl+c":
+ return m, tea.Quit
+ case "?":
+ m.help = !m.help
+ case "c":
+ m.commands = !m.commands
+ case "/":
+ m.searching = true
+ case "r":
+ m.viewport.GotoTop()
+ return m, loadSnapshot(m.cwd)
+ case "a":
+ m.agent = m.nextAgentFilter()
+ m.selected = 0
+ m.viewport.GotoTop()
+ case "tab", "right", "l":
+ m.filter = (m.filter + 1) % 3
+ m.selected = 0
+ m.viewport.GotoTop()
+ case "shift+tab", "left", "h":
+ m.filter = (m.filter + 2) % 3
+ m.selected = 0
+ m.viewport.GotoTop()
+ case "down", "j":
+ m.selected++
+ m.viewport.GotoTop()
+ case "up", "k":
+ m.selected--
+ m.viewport.GotoTop()
+ case "pgdown", "ctrl+d":
+ var cmd tea.Cmd
+ m.viewport, cmd = m.viewport.Update(msg)
+ return m, cmd
+ case "pgup", "ctrl+u":
+ var cmd tea.Cmd
+ m.viewport, cmd = m.viewport.Update(msg)
+ return m, cmd
+ case "home":
+ m.viewport.GotoTop()
+ }
+ m.clampSelection()
+ m.syncViewport()
+ }
+ return m, nil
+}
+
+func (m *appModel) syncViewport() {
+ _, _, detailOuter := paneOuterWidths(max(1, m.width))
+ detailInner := max(1, detailOuter-4)
+ innerHeight := max(1, max(8, m.height-2)-2)
+ m.viewport.Width = detailInner
+ m.viewport.Height = innerHeight
+ m.viewport.SetContent(m.detailText(detailInner))
+}
+
+func (m *appModel) clampSelection() {
+ items := m.filteredSkills()
+ if len(items) == 0 {
+ m.selected = 0
+ return
+ }
+ if m.selected < 0 {
+ m.selected = 0
+ }
+ if m.selected >= len(items) {
+ m.selected = len(items) - 1
+ }
+}
+
+func (m appModel) View() string {
+ if m.err != nil {
+ return errorStyle.Render(fmt.Sprintf("LazySkills error: %s\n\nPress q to quit.", compat.SanitizeMetadata(m.err.Error())))
+ }
+ if m.width == 0 {
+ m.width = 100
+ }
+ if m.height == 0 {
+ m.height = 32
+ }
+
+ outerHeight := max(8, m.height-2)
+ innerHeight := max(1, outerHeight-2)
+ leftOuter, listOuter, detailOuter := paneOuterWidths(m.width)
+ leftInner := max(1, leftOuter-4)
+ listInner := max(1, listOuter-4)
+ detailInner := max(1, detailOuter-4)
+
+ leftStyle := borderStyle.Width(leftInner).MaxWidth(leftInner).Height(innerHeight).MaxHeight(innerHeight)
+ listStyle := borderStyle.Width(listInner).MaxWidth(listInner).Height(innerHeight).MaxHeight(innerHeight)
+ detailStyle := borderStyle.Width(detailInner).MaxWidth(detailInner).Height(innerHeight).MaxHeight(innerHeight)
+ left := leftStyle.Render(fitLines(m.filterPane(), innerHeight))
+ list := listStyle.Render(fitLines(m.listPane(innerHeight), innerHeight))
+ detail := detailStyle.Render(m.detailPane(innerHeight, detailInner))
+ footer := m.footer()
+ return lipgloss.JoinHorizontal(lipgloss.Top, left, list, detail) + "\n" + footer
+}
+
+func (m appModel) filterPane() string {
+ counts := map[model.Scope]int{}
+ issues := 0
+ for _, sk := range m.result.Skills {
+ counts[sk.Scope]++
+ issues += len(sk.HealthIssues)
+ }
+ issues += len(m.result.HealthIssues)
+ lines := []string{
+ titleStyle.Render("LazySkills"),
+ dimStyle.Render(compat.SanitizeMetadata(m.result.Cwd)),
+ "",
+ filterLine("All", m.filter == scopeAll),
+ filterLine(fmt.Sprintf("Project (%d)", counts[model.ScopeProject]), m.filter == scopeProject),
+ filterLine(fmt.Sprintf("Global (%d)", counts[model.ScopeGlobal]), m.filter == scopeGlobal),
+ "",
+ fmt.Sprintf("Skills: %d", len(m.result.Skills)),
+ fmt.Sprintf("Issues: %d", issues),
+ fmt.Sprintf("Agent: %s", m.agentLabel()),
+ }
+ if len(m.result.HealthIssues) > 0 {
+ lines = append(lines, "", errorStyle.Render("Scan health"))
+ for _, issue := range m.result.HealthIssues {
+ lines = append(lines, truncate(fmt.Sprintf("- %s: %s", compat.SanitizeMetadata(issue.Type), compat.SanitizeMetadata(issue.Message)), 36))
+ }
+ }
+ if m.search != "" || m.searching {
+ prompt := "/" + compat.SanitizeMetadata(m.search)
+ if m.searching {
+ prompt += "_"
+ }
+ lines = append(lines, "", "Search", prompt)
+ }
+ if m.help {
+ lines = append(lines, "", "Keys", "↑/↓ j/k select", "tab scope", "a agent", "c commands", "/ search", "r refresh", "? help", "q quit")
+ }
+ return strings.Join(lines, "\n")
+}
+
+func filterLine(label string, active bool) string {
+ if active {
+ return selectedStyle.Render("› " + label)
+ }
+ return " " + label
+}
+
+func (m appModel) listPane(height int) string {
+ items := m.filteredSkills()
+ lines := []string{titleStyle.Render("Skills")}
+ if len(items) == 0 {
+ detail := "No skills match."
+ if m.agent != "" {
+ detail += fmt.Sprintf(" %s has no visible skills for this view.", m.agentLabel())
+ }
+ if m.search != "" {
+ detail += " Clear search with backspace."
+ }
+ return strings.Join(append(lines, "", dimStyle.Render(detail)), "\n")
+ }
+ visible := max(1, height-3)
+ start := 0
+ if m.selected >= visible {
+ start = m.selected - visible + 1
+ }
+ end := min(len(items), start+visible)
+ for i := start; i < end; i++ {
+ view := display.Skill(items[i])
+ label := fmt.Sprintf("%s [%s]", view.Name, view.Scope)
+ if len(view.HealthIssues) > 0 {
+ label += fmt.Sprintf(" !%d", len(view.HealthIssues))
+ }
+ if i == m.selected {
+ lines = append(lines, selectedStyle.Render(truncate(label, 48)))
+ } else {
+ lines = append(lines, truncate(label, 48))
+ }
+ }
+ return strings.Join(lines, "\n")
+}
+
+func (m appModel) detailPane(height, width int) string {
+ if m.viewport.Width != width || m.viewport.Height != height || m.viewport.View() == "" {
+ m.viewport.Width = width
+ m.viewport.Height = height
+ m.viewport.SetContent(m.detailText(width))
+ }
+ return m.viewport.View()
+}
+
+func (m appModel) detailText(width int) string {
+ return strings.Join(m.detailLines(width), "\n")
+}
+
+func (m appModel) detailLines(width int) []string {
+ items := m.filteredSkills()
+ if len(items) == 0 {
+ return []string{titleStyle.Render("Details"), "", dimStyle.Render("Select a skill to inspect it.")}
+ }
+ view := display.Skill(items[m.selected])
+ lines := []string{
+ titleStyle.Render(view.Name),
+ wrapText(view.Description, width),
+ "",
+ fmt.Sprintf("Scope: %s", view.Scope),
+ wrapText(fmt.Sprintf("Lock: %s", display.LockSummary(view)), width),
+ }
+ if view.CanonicalPath != "" {
+ lines = append(lines, wrapText("Canonical: "+view.CanonicalPath, width))
+ }
+ if m.agent != "" {
+ lines = append(lines, "Agent filter: "+m.agentLabel())
+ }
+ lines = append(lines, "", "Observed")
+ for _, p := range view.Observed {
+ line := fmt.Sprintf("- %s %s %s", p.Agent, p.Scope, p.Status)
+ if p.TargetPath != "" {
+ line += " → " + p.TargetPath
+ }
+ lines = append(lines, wrapText(line, width))
+ }
+ if len(view.HealthIssues) == 0 {
+ // no-op
+ } else {
+ lines = append(lines, "", errorStyle.Render("Health"))
+ for _, issue := range view.HealthIssues {
+ line := fmt.Sprintf("- %s: %s", issue.Type, issue.Message)
+ if issue.Path != "" {
+ line += " (" + issue.Path + ")"
+ }
+ lines = append(lines, wrapText(line, width))
+ }
+ }
+ if m.commands {
+ lines = append(lines, "")
+ lines = append(lines, m.commandPreview(items[m.selected], width-4)...)
+ return lines
+ }
+ if view.Preview != "" {
+ lines = append(lines, "", "Preview")
+ previewLines := strings.Split(view.Preview, "\n")
+ for _, line := range previewLines {
+ lines = append(lines, wrapText(line, width))
+ }
+ }
+ return lines
+}
+
+func (m appModel) commandPreview(sk *model.Skill, width int) []string {
+ lines := []string{titleStyle.Render("Command previews")}
+ lines = append(lines, dimStyle.Render("Preview only. LazySkills will not run these commands yet."))
+ for _, preview := range actions.ForSkill(sk) {
+ if !preview.Available {
+ lines = append(lines, "", fmt.Sprintf("%s (unavailable)", compat.SanitizeMetadata(preview.Title)))
+ lines = append(lines, wrap(compat.SanitizeMetadata(preview.Reason), width))
+ continue
+ }
+ marker := "read-only"
+ if preview.Mutates {
+ marker = "mutates"
+ }
+ lines = append(lines, "", fmt.Sprintf("%s (%s)", compat.SanitizeMetadata(preview.Title), marker))
+ lines = append(lines, truncate(compat.SanitizeMetadata(preview.Command), width))
+ if preview.Description != "" {
+ lines = append(lines, wrap(compat.SanitizeMetadata(preview.Description), width))
+ }
+ }
+ return lines
+}
+
+func (m appModel) footer() string {
+ mode := ""
+ if m.searching {
+ mode = " search mode: type to filter, esc/enter to leave"
+ } else if m.commands {
+ mode = " command previews: c to hide"
+ }
+ return dimStyle.Render("LazySkills is read-only." + mode)
+}
+
+func (m appModel) filteredSkills() []*model.Skill {
+ query := strings.ToLower(m.search)
+ out := make([]*model.Skill, 0, len(m.result.Skills))
+ for _, sk := range m.result.Skills {
+ if m.filter == scopeProject && sk.Scope != model.ScopeProject {
+ continue
+ }
+ if m.filter == scopeGlobal && sk.Scope != model.ScopeGlobal {
+ continue
+ }
+ if m.agent != "" && !skillObservedByAgent(sk, m.agent) {
+ continue
+ }
+ if query != "" {
+ view := display.Skill(sk)
+ haystack := strings.ToLower(view.Name + " " + view.Description)
+ if !strings.Contains(haystack, query) {
+ continue
+ }
+ }
+ out = append(out, sk)
+ }
+ return out
+}
+
+func (m appModel) agentFilters() []string {
+ ids := []string{}
+ for _, agent := range agents.InitialAgents() {
+ if agent.Name == "universal" {
+ continue
+ }
+ ids = append(ids, agent.Name)
+ }
+ sort.Strings(ids)
+ return ids
+}
+
+func (m appModel) nextAgentFilter() string {
+ agents := m.agentFilters()
+ if len(agents) == 0 {
+ return ""
+ }
+ if m.agent == "" {
+ return agents[0]
+ }
+ for i, agent := range agents {
+ if agent == m.agent {
+ if i == len(agents)-1 {
+ return ""
+ }
+ return agents[i+1]
+ }
+ }
+ return ""
+}
+
+func skillObservedByAgent(sk *model.Skill, agent string) bool {
+ for _, observed := range sk.ObservedPaths {
+ if compat.SanitizeMetadata(observed.Agent) == agent {
+ return true
+ }
+ }
+ return false
+}
+
+func (m appModel) agentLabel() string {
+ if m.agent == "" {
+ return "all"
+ }
+ for _, agent := range agents.InitialAgents() {
+ if agent.Name == m.agent {
+ return compat.SanitizeMetadata(agent.Display)
+ }
+ }
+ return compat.SanitizeMetadata(m.agent)
+}
+
+func wrap(s string, width int) string {
+ if width <= 8 || len(s) <= width {
+ return s
+ }
+ words := strings.Fields(s)
+ lines := []string{}
+ current := ""
+ for _, word := range words {
+ if len(current)+len(word)+1 > width {
+ lines = append(lines, current)
+ current = word
+ } else if current == "" {
+ current = word
+ } else {
+ current += " " + word
+ }
+ }
+ if current != "" {
+ lines = append(lines, current)
+ }
+ return strings.Join(lines, "\n")
+}
+
+func wrapText(s string, width int) string {
+ if width <= 1 {
+ return ""
+ }
+ s = strings.ReplaceAll(s, "\t", " ")
+ return wordwrap.String(s, width)
+}
+
+func truncate(s string, width int) string {
+ runes := []rune(s)
+ if width <= 1 || len(runes) <= width {
+ return s
+ }
+ return string(runes[:width-1]) + "…"
+}
+
+func fitLines(s string, height int) string {
+ if height <= 0 {
+ return ""
+ }
+ lines := strings.Split(s, "\n")
+ if len(lines) <= height {
+ return s
+ }
+ return strings.Join(lines[:height], "\n")
+}
+
+func fitToScreen(s string, width, height int) string {
+ if width <= 0 || height <= 0 {
+ return ""
+ }
+ lines := strings.Split(s, "\n")
+ if len(lines) > height {
+ lines = lines[:height]
+ }
+ for i, line := range lines {
+ for lipgloss.Width(line) > width {
+ runes := []rune(line)
+ if len(runes) == 0 {
+ break
+ }
+ line = string(runes[:len(runes)-1])
+ }
+ lines[i] = line
+ }
+ return strings.Join(lines, "\n")
+}
+
+func min(a, b int) int {
+ if a < b {
+ return a
+ }
+ return b
+}
+
+func max(a, b int) int {
+ if a > b {
+ return a
+ }
+ return b
+}
+
+func paneOuterWidths(total int) (left, list, detail int) {
+ if total < 60 {
+ left = max(16, total/4)
+ list = max(20, total/3)
+ } else {
+ left = max(24, total/4)
+ list = max(28, total/3)
+ }
+ if left+list > total-20 {
+ left = max(12, total/5)
+ list = max(18, total/3)
+ }
+ detail = total - left - list
+ if detail < 20 {
+ detail = 20
+ list = max(12, total-left-detail)
+ }
+ if left+list+detail > total {
+ detail = max(1, total-left-list)
+ }
+ return left, list, detail
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, value := range values {
+ if value != "" {
+ return value
+ }
+ }
+ return ""
+}
diff --git a/internal/tui/tui_test.go b/internal/tui/tui_test.go
new file mode 100644
index 0000000..4fa0a43
--- /dev/null
+++ b/internal/tui/tui_test.go
@@ -0,0 +1,162 @@
+package tui
+
+import (
+ "errors"
+ "strings"
+ "testing"
+
+ tea "github.com/charmbracelet/bubbletea"
+ "github.com/charmbracelet/lipgloss"
+
+ "lazyskills/internal/model"
+)
+
+func TestFilteredSkillsUsesSanitizedSearch(t *testing.T) {
+ m := appModel{
+ search: "bad name",
+ result: model.ScanResult{Skills: []*model.Skill{{
+ Name: "Bad\x1b[31m Name",
+ Description: "desc",
+ Scope: model.ScopeProject,
+ }}},
+ }
+ items := m.filteredSkills()
+ if len(items) != 1 {
+ t.Fatalf("expected sanitized search to match, got %d", len(items))
+ }
+}
+
+func TestErrorViewIsSanitized(t *testing.T) {
+ m := appModel{err: errors.New("bad\x1b[31m path")}
+ out := m.View()
+ if strings.Contains(out, "\x1b[31m") || strings.Contains(out, "\x1b") {
+ t.Fatalf("expected sanitized error view, got %q", out)
+ }
+ if !strings.Contains(out, "bad path") {
+ t.Fatalf("expected sanitized error text, got %q", out)
+ }
+}
+
+func TestViewRendersReadOnlyFooter(t *testing.T) {
+ m := appModel{width: 100, height: 30, result: model.ScanResult{Skills: []*model.Skill{{Name: "Build", Description: "Build desc", Scope: model.ScopeProject}}}}
+ out := m.View()
+ if !strings.Contains(out, "LazySkills is read-only") || !strings.Contains(out, "Build") {
+ t.Fatalf("unexpected view: %s", out)
+ }
+}
+
+func TestAgentFilterLimitsVisibleSkills(t *testing.T) {
+ m := appModel{agent: "opencode", result: model.ScanResult{Skills: []*model.Skill{
+ {Name: "OpenCode Skill", Description: "desc", Scope: model.ScopeProject, ObservedPaths: []model.ObservedPath{{Agent: "opencode"}}},
+ {Name: "Claude Skill", Description: "desc", Scope: model.ScopeProject, ObservedPaths: []model.ObservedPath{{Agent: "claude-code"}}},
+ }}}
+ items := m.filteredSkills()
+ if len(items) != 1 || items[0].Name != "OpenCode Skill" {
+ t.Fatalf("unexpected filtered skills: %#v", items)
+ }
+}
+
+func TestNextAgentFilterCyclesThroughObservedAgents(t *testing.T) {
+ m := appModel{result: model.ScanResult{Skills: []*model.Skill{
+ {Name: "A", ObservedPaths: []model.ObservedPath{{Agent: "opencode"}, {Agent: "cursor"}}},
+ }}}
+ first := m.nextAgentFilter()
+ if first != "claude-code" {
+ t.Fatalf("expected first supported agent claude-code, got %q", first)
+ }
+ m.agent = first
+ second := m.nextAgentFilter()
+ if second != "codex" {
+ t.Fatalf("expected second supported agent codex, got %q", second)
+ }
+ m.agent = "opencode"
+ if got := m.nextAgentFilter(); got != "" {
+ t.Fatalf("expected cycle back to all, got %q", got)
+ }
+}
+
+func TestAgentFilterCanSelectSupportedAgentWithNoSkills(t *testing.T) {
+ m := appModel{width: 100, height: 30, agent: "claude-code", result: model.ScanResult{Skills: []*model.Skill{
+ {Name: "OpenCode Skill", Description: "desc", Scope: model.ScopeProject, ObservedPaths: []model.ObservedPath{{Agent: "opencode"}}},
+ }}}
+ items := m.filteredSkills()
+ if len(items) != 0 {
+ t.Fatalf("expected no skills for claude-code, got %#v", items)
+ }
+ out := m.View()
+ if !strings.Contains(out, "Claude Code") || !strings.Contains(out, "has no visible skills") {
+ t.Fatalf("expected zero-skill agent empty state, got %q", out)
+ }
+}
+
+func TestTopLevelScanHealthIsRenderedSanitized(t *testing.T) {
+ m := appModel{width: 100, height: 30, result: model.ScanResult{HealthIssues: []model.HealthIssue{{Type: "corrupt_lock", Message: "bad\x1b[31m lock"}}}}
+ out := m.View()
+ if !strings.Contains(out, "Scan health") || !strings.Contains(out, "bad") || !strings.Contains(out, "lock") {
+ t.Fatalf("expected scan health in output: %q", out)
+ }
+ if strings.Contains(out, "\x1b[31m") || strings.ContainsRune(out, '\x1b') {
+ t.Fatalf("expected sanitized scan health: %q", out)
+ }
+}
+
+func TestCommandPreviewModeRendersWithoutExecuting(t *testing.T) {
+ m := appModel{width: 120, height: 40, commands: true, result: model.ScanResult{Skills: []*model.Skill{{
+ Name: "Deploy Skill",
+ Scope: model.ScopeProject,
+ LocalLock: &model.LocalLockEntry{Source: "owner/repo"},
+ }}}}
+ out := m.View()
+ if !strings.Contains(out, "Command previews") || !strings.Contains(out, "Preview only") || !strings.Contains(out, "npx skills") {
+ t.Fatalf("expected command previews in output: %q", out)
+ }
+}
+
+func TestCommandPreviewToggle(t *testing.T) {
+ m := appModel{}
+ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune{'c'}})
+ next := updated.(appModel)
+ if !next.commands {
+ t.Fatalf("expected command preview mode enabled")
+ }
+}
+
+func TestDetailPaneClipsLongPreview(t *testing.T) {
+ preview := strings.Repeat("line\n", 80)
+ m := appModel{width: 100, height: 20, result: model.ScanResult{Skills: []*model.Skill{{Name: "Long", Description: "desc", Scope: model.ScopeProject, Preview: preview}}}}
+ out := m.detailPane(8, 40)
+ lines := strings.Split(out, "\n")
+ if len(lines) > 8 {
+ t.Fatalf("detail pane overflowed: got %d lines\n%s", len(lines), out)
+ }
+}
+
+func TestDetailScrollKeysMoveViewport(t *testing.T) {
+ preview := strings.Repeat("line\n", 80)
+ m := appModel{width: 100, height: 20, result: model.ScanResult{Skills: []*model.Skill{{Name: "Long", Description: "desc", Scope: model.ScopeProject, Preview: preview}}}}
+ m.syncViewport()
+ updated, _ := m.Update(tea.KeyMsg{Type: tea.KeyPgDown})
+ next := updated.(appModel)
+ if next.viewport.YOffset <= 0 {
+ t.Fatalf("expected detail scroll to move down, got %d", next.viewport.YOffset)
+ }
+ updated, _ = next.Update(tea.KeyMsg{Type: tea.KeyHome})
+ next = updated.(appModel)
+ if next.viewport.YOffset != 0 {
+ t.Fatalf("expected home to reset detail scroll, got %d", next.viewport.YOffset)
+ }
+}
+
+func TestFullViewFitsTerminalDimensionsWithLongPreview(t *testing.T) {
+ preview := strings.Repeat("a very long line that should be clipped and not wrap the entire screen\n", 120)
+ m := appModel{width: 100, height: 24, result: model.ScanResult{Skills: []*model.Skill{{Name: "Long", Description: strings.Repeat("description ", 30), Scope: model.ScopeProject, Preview: preview}}}}
+ out := m.View()
+ if got := lipgloss.Height(out); got > 24 {
+ t.Fatalf("view height overflowed: got %d want <= 24\n%s", got, out)
+ }
+ for i, line := range strings.Split(out, "\n") {
+ if width := lipgloss.Width(line); width > 100 {
+ t.Fatalf("line %d width overflowed: got %d want <= 100\n%s", i, width, line)
+ }
+ }
+}