From 402ec082434745d8696c03c214ed09285f1628f8 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Wed, 25 Nov 2026 18:43:24 +0000 Subject: [PATCH 01/25] Add a skills source interface over fs.FS Skill sources need the manifest type and its path checks, and the libs-no-aitools lint rule keeps shared libs from importing the installer. Move Manifest, SkillMeta, NormalizeManifest, CheckManifestPaths, EscapesDir and ErrUnsafeManifestPath down into libs/skills; the installer uses them from there through aliases. Add the Skill and Catalog types, the Source interface, sentinel errors, and NewFSSource over any fs.FS laid out like a skills release. The manifest accepts optional per-skill commands and a top-level catalog_rules file. Co-authored-by: Isaac --- libs/aitools/installer/errors.go | 4 +- libs/aitools/installer/installer.go | 38 ++---- libs/aitools/installer/installer_test.go | 3 +- libs/aitools/installer/source.go | 62 +-------- libs/aitools/installer/source_test.go | 13 +- libs/skills/fs.go | 97 +++++++++++++ libs/skills/fs_test.go | 128 ++++++++++++++++++ libs/skills/manifest.go | 118 ++++++++++++++++ libs/skills/skills.go | 60 ++++++++ libs/skills/testdata/release/RULES.md | 1 + .../release/experimental/beta/SKILL.md | 6 + libs/skills/testdata/release/manifest.json | 8 ++ .../testdata/release/skills/alpha/SKILL.md | 6 + .../release/skills/alpha/references/guide.md | 3 + 14 files changed, 450 insertions(+), 97 deletions(-) create mode 100644 libs/skills/fs.go create mode 100644 libs/skills/fs_test.go create mode 100644 libs/skills/manifest.go create mode 100644 libs/skills/skills.go create mode 100644 libs/skills/testdata/release/RULES.md create mode 100644 libs/skills/testdata/release/experimental/beta/SKILL.md create mode 100644 libs/skills/testdata/release/manifest.json create mode 100644 libs/skills/testdata/release/skills/alpha/SKILL.md create mode 100644 libs/skills/testdata/release/skills/alpha/references/guide.md diff --git a/libs/aitools/installer/errors.go b/libs/aitools/installer/errors.go index 0f4c9a5b539..aa8ac3c69e9 100644 --- a/libs/aitools/installer/errors.go +++ b/libs/aitools/installer/errors.go @@ -4,6 +4,8 @@ import ( "errors" "fmt" "net/http" + + "github.com/databricks/cli/libs/skills" ) // ErrNothingInstalled reports that update or uninstall found no install state @@ -82,7 +84,7 @@ var ErrManifestTooLarge = fmt.Errorf("skills manifest is larger than %d MiB", ma // ErrUnsafeManifestPath reports a skills manifest that names a skill or file // outside the skills directory. The command layer classifies it like a // manifest that does not parse. -var ErrUnsafeManifestPath = errors.New("skills manifest names a path outside the skills directory") +var ErrUnsafeManifestPath = skills.ErrUnsafeManifestPath // Stages of fetching skills content, recorded on FetchError so a failed // release lookup can be told apart from a failed download. diff --git a/libs/aitools/installer/installer.go b/libs/aitools/installer/installer.go index ae6f67a7be3..9dc4e59ae70 100644 --- a/libs/aitools/installer/installer.go +++ b/libs/aitools/installer/installer.go @@ -26,6 +26,7 @@ import ( "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/log" + "github.com/databricks/cli/libs/skills" "github.com/databricks/cli/libs/versioncheck" "golang.org/x/mod/semver" "golang.org/x/sync/errgroup" @@ -34,8 +35,8 @@ import ( const ( skillsRepoOwner = "databricks" skillsRepoName = "databricks-agent-skills" - stableSkillsRepoPath = "skills" - experimentalRepoPath = "experimental" + stableSkillsRepoPath = skills.StableRepoDir + experimentalRepoPath = skills.ExperimentalRepoDir // fetchConcurrency caps the number of in-flight skill file fetches. // Each file is one HTTPS GET to raw.githubusercontent.com; sequential @@ -194,32 +195,11 @@ func GetSkillsBaseURL(ctx context.Context) string { return "https://raw.githubusercontent.com/" + skillsRepoOwner + "/" + skillsRepoName } -// Manifest describes the skills manifest fetched from the skills repo. -type Manifest struct { - Version string `json:"version"` - UpdatedAt string `json:"updated_at"` - Skills map[string]SkillMeta `json:"skills"` -} - -// SkillMeta describes a single skill entry in the manifest. -type SkillMeta struct { - Version string `json:"version"` - UpdatedAt string `json:"updated_at"` - Files []string `json:"files"` - Description string `json:"description,omitempty"` - MinCLIVer string `json:"min_cli_version,omitempty"` - - // RepoDir is "skills" or "experimental" (manifest field repo_dir). - RepoDir string `json:"repo_dir,omitempty"` - - // SourceName is the upstream skill directory name within RepoDir. - // Set during normalization, not from JSON. - SourceName string `json:"-"` -} - -func (s SkillMeta) IsExperimental() bool { - return s.RepoDir == experimentalRepoPath -} +// Manifest and SkillMeta are defined in libs/skills, which the skill sources share. +type ( + Manifest = skills.Manifest + SkillMeta = skills.SkillMeta +) // InstallOptions controls the behavior of InstallSkillsForAgents. type InstallOptions struct { @@ -281,7 +261,7 @@ func FetchSkillsManifestWithFallback(ctx context.Context, src ManifestSource, re if err != nil { return nil, ref, err } - if err := checkManifestPaths(manifest); err != nil { + if err := skills.CheckManifestPaths(manifest); err != nil { return nil, ref, err } return manifest, ref, nil diff --git a/libs/aitools/installer/installer_test.go b/libs/aitools/installer/installer_test.go index 5f9fe9e0235..483a27c6d18 100644 --- a/libs/aitools/installer/installer_test.go +++ b/libs/aitools/installer/installer_test.go @@ -24,6 +24,7 @@ import ( "github.com/databricks/cli/libs/clicompat" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/log" + "github.com/databricks/cli/libs/skills" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -40,7 +41,7 @@ func (m *mockManifestSource) FetchManifest(_ context.Context, _ string) (*Manife if m.fetchErr != nil { return nil, m.fetchErr } - normalizeManifest(m.manifest) + skills.NormalizeManifest(m.manifest) return m.manifest, nil } diff --git a/libs/aitools/installer/source.go b/libs/aitools/installer/source.go index 0cc06e1fa62..8476ce9485c 100644 --- a/libs/aitools/installer/source.go +++ b/libs/aitools/installer/source.go @@ -5,17 +5,16 @@ import ( "encoding/json" "fmt" "io" - "maps" "net/http" "path" "regexp" - "slices" "strings" "sync" "time" "github.com/databricks/cli/libs/clicompat" "github.com/databricks/cli/libs/log" + "github.com/databricks/cli/libs/skills" ) // ManifestSource abstracts how the skills manifest is fetched. @@ -69,7 +68,7 @@ func (s *GitHubManifestSource) FetchManifest(ctx context.Context, ref string) (* return nil, &FetchError{Stage: FetchStageManifest, StatusCode: resp.StatusCode, Err: fmt.Errorf("failed to parse manifest: %w", err)} } - normalizeManifest(&manifest) + skills.NormalizeManifest(&manifest) return &manifest, nil } @@ -86,49 +85,6 @@ var skillNamePattern = sync.OnceValue(func() *regexp.Regexp { return regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`) }) -// checkManifestPaths fails a manifest that names a skill or file outside its -// directory, or a skill named like the state file. The manifest comes from the -// network, so it must not be able to name ../../.bashrc, and only a broken or -// tampered manifest lists such an entry. The rule is the same on every OS. -// Entries that stay inside their directory but are not portable are left to -// unportableSkill, which skips only that skill. -func checkManifestPaths(m *Manifest) error { - for _, name := range slices.Sorted(maps.Keys(m.Skills)) { - if name == "" || name == "." || name == ".." || name == stateFileName || strings.ContainsAny(name, `/\`) { - return fmt.Errorf("%w: skill name %q", ErrUnsafeManifestPath, name) - } - for _, file := range m.Skills[name].Files { - if escapesDir(file) { - return fmt.Errorf("%w: skill %q lists file %q", ErrUnsafeManifestPath, name, file) - } - } - } - return nil -} - -// escapesDir reports whether file, joined onto a directory, names a path -// outside it on some OS: an absolute path, a Windows drive, or more ".." -// elements than the elements before them, with either slash as the separator. -func escapesDir(file string) bool { - if strings.HasPrefix(file, "/") || strings.HasPrefix(file, `\`) || (len(file) >= 2 && file[1] == ':') { - return true - } - depth := 0 - for _, elem := range strings.FieldsFunc(file, func(r rune) bool { return r == '/' || r == '\\' }) { - switch elem { - case ".": - case "..": - depth-- - if depth < 0 { - return true - } - default: - depth++ - } - } - return false -} - // unportableSkill returns why a skill that stays inside its directory still // cannot be installed the same way on every OS, or "" if it can. Install skips // such a skill and update keeps the installed copy, the way both treat a skill @@ -207,17 +163,3 @@ func isWindowsDeviceName(s string) bool { } return false } - -// normalizeManifest stamps SourceName and defaults RepoDir for older manifests. -func normalizeManifest(m *Manifest) { - if m.Skills == nil { - m.Skills = map[string]SkillMeta{} - } - for name, meta := range m.Skills { - if meta.RepoDir == "" { - meta.RepoDir = stableSkillsRepoPath - } - meta.SourceName = name - m.Skills[name] = meta - } -} diff --git a/libs/aitools/installer/source_test.go b/libs/aitools/installer/source_test.go index dbe96be9a54..eda631cd152 100644 --- a/libs/aitools/installer/source_test.go +++ b/libs/aitools/installer/source_test.go @@ -11,6 +11,7 @@ import ( "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/skills" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -23,7 +24,7 @@ func TestNormalizeManifestStampsSourceNameAndRepoDir(t *testing.T) { }, } - normalizeManifest(m) + skills.NormalizeManifest(m) stable := m.Skills["databricks-apps"] assert.False(t, stable.IsExperimental()) @@ -41,7 +42,7 @@ func TestManifestHasExperimental(t *testing.T) { stableOnly := &Manifest{Skills: map[string]SkillMeta{ "databricks-apps": {Version: "0.1.0"}, }} - normalizeManifest(stableOnly) + skills.NormalizeManifest(stableOnly) assert.False(t, manifestHasExperimental(stableOnly)) withExperimental := &Manifest{ @@ -50,7 +51,7 @@ func TestManifestHasExperimental(t *testing.T) { "databricks-iceberg": {Version: "0.0.1", RepoDir: experimentalRepoPath}, }, } - normalizeManifest(withExperimental) + skills.NormalizeManifest(withExperimental) assert.True(t, manifestHasExperimental(withExperimental)) } @@ -61,7 +62,7 @@ func TestNormalizeManifestOnlyExperimentalSkills(t *testing.T) { }, } - normalizeManifest(m) + skills.NormalizeManifest(m) got, ok := m.Skills["x"] assert.True(t, ok) @@ -177,7 +178,7 @@ func TestCheckManifestPaths(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { m := &Manifest{Skills: map[string]SkillMeta{tc.skill: {Files: []string{tc.file}}}} - err := checkManifestPaths(m) + err := skills.CheckManifestPaths(m) if tc.wantErr != "" { require.ErrorIs(t, err, ErrUnsafeManifestPath) assert.EqualError(t, err, ErrUnsafeManifestPath.Error()+": "+tc.wantErr) @@ -218,7 +219,7 @@ func TestCheckManifestPathsReportsTheFirstSkillInOrder(t *testing.T) { "../c": {Files: []string{"SKILL.md"}}, }} for range 10 { - assert.EqualError(t, checkManifestPaths(m), ErrUnsafeManifestPath.Error()+`: skill name "../c"`) + assert.EqualError(t, skills.CheckManifestPaths(m), ErrUnsafeManifestPath.Error()+`: skill name "../c"`) } } diff --git a/libs/skills/fs.go b/libs/skills/fs.go new file mode 100644 index 00000000000..e3575915796 --- /dev/null +++ b/libs/skills/fs.go @@ -0,0 +1,97 @@ +package skills + +import ( + "context" + "encoding/json" + "fmt" + "io/fs" + "maps" + "path" + "slices" + "time" +) + +const manifestFile = "manifest.json" + +type fsSource struct { + fsys fs.FS + label string +} + +// NewFSSource returns a Source over fsys, laid out like a skills release: +// manifest.json at the root, and each skill's files under its repo_dir. +func NewFSSource(fsys fs.FS, label string) Source { + return &fsSource{fsys: fsys, label: label} +} + +func (s *fsSource) Catalog(_ context.Context) (*Catalog, error) { + m, err := s.manifest() + if err != nil { + return nil, err + } + catalog := &Catalog{Version: m.Version, Label: s.label, FetchedAt: time.Now()} + if m.CatalogRules != "" { + data, err := fs.ReadFile(s.fsys, m.CatalogRules) + if err != nil { + return nil, fmt.Errorf("read catalog_rules: %w", err) + } + catalog.Rules = string(data) + } + for _, name := range slices.Sorted(maps.Keys(m.Skills)) { + meta := m.Skills[name] + catalog.Skills = append(catalog.Skills, Skill{ + Name: name, + Description: meta.Description, + Version: meta.Version, + Files: meta.Files, + Commands: meta.Commands, + Experimental: meta.IsExperimental(), + }) + } + return catalog, nil +} + +func (s *fsSource) ReadFile(_ context.Context, skill, file string) ([]byte, error) { + m, err := s.manifest() + if err != nil { + return nil, err + } + meta, ok := m.Skills[skill] + if !ok { + return nil, fmt.Errorf("%w: %q", ErrUnknownSkill, skill) + } + if !slices.Contains(meta.Files, file) { + return nil, fmt.Errorf("%w: %q in skill %q", ErrUnknownFile, file, skill) + } + data, err := fs.ReadFile(s.fsys, path.Join(meta.RepoDir, skill, file)) + if err != nil { + return nil, fmt.Errorf("read %q in skill %q: %w", file, skill, err) + } + return data, nil +} + +// manifest reads and checks the release manifest. Every path it names, the +// skill files, repo_dir and catalog_rules, must stay inside the release. +func (s *fsSource) manifest() (*Manifest, error) { + data, err := fs.ReadFile(s.fsys, manifestFile) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrSourceUnreachable, err) + } + var m Manifest + if err := json.Unmarshal(data, &m); err != nil { + return nil, fmt.Errorf("parse %s: %w", manifestFile, err) + } + NormalizeManifest(&m) + if err := CheckManifestPaths(&m); err != nil { + return nil, err + } + for _, name := range slices.Sorted(maps.Keys(m.Skills)) { + if repoDir := m.Skills[name].RepoDir; EscapesDir(repoDir) { + return nil, fmt.Errorf("%w: skill %q has repo_dir %q", ErrUnsafeManifestPath, name, repoDir) + } + } + if EscapesDir(m.CatalogRules) { + return nil, fmt.Errorf("%w: catalog_rules %q", ErrUnsafeManifestPath, m.CatalogRules) + } + return &m, nil +} diff --git a/libs/skills/fs_test.go b/libs/skills/fs_test.go new file mode 100644 index 00000000000..93426406fa5 --- /dev/null +++ b/libs/skills/fs_test.go @@ -0,0 +1,128 @@ +package skills + +import ( + "os" + "testing" + "testing/fstest" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func fixtureSource() Source { + return NewFSSource(os.DirFS("testdata/release"), "test release") +} + +func mapSource(manifest string) Source { + return NewFSSource(fstest.MapFS{"manifest.json": {Data: []byte(manifest)}}, "map") +} + +func TestCatalogFromFixture(t *testing.T) { + catalog, err := fixtureSource().Catalog(t.Context()) + require.NoError(t, err) + + assert.Equal(t, "1.2.0", catalog.Version) + assert.Equal(t, "test release", catalog.Label) + assert.False(t, catalog.Stale) + assert.False(t, catalog.FetchedAt.IsZero()) + assert.Equal(t, "Use the catalog before you read a skill.\n", catalog.Rules) + + require.Len(t, catalog.Skills, 2) + assert.Equal(t, Skill{ + Name: "alpha", + Description: "A stable skill with a nested file.", + Version: "1.0.0", + Files: []string{"SKILL.md", "references/guide.md"}, + Commands: []string{"jobs", "pipelines"}, + }, catalog.Skills[0]) + assert.Equal(t, Skill{ + Name: "beta", + Description: "An experimental skill.", + Version: "0.1.0", + Files: []string{"SKILL.md"}, + Experimental: true, + }, catalog.Skills[1]) +} + +func TestReadFiles(t *testing.T) { + src := fixtureSource() + + data, err := src.ReadFile(t.Context(), "alpha", "SKILL.md") + require.NoError(t, err) + assert.Contains(t, string(data), "# Alpha") + + data, err = src.ReadFile(t.Context(), "alpha", "references/guide.md") + require.NoError(t, err) + assert.Equal(t, "# Guide\n\nRead this for details.\n", string(data)) + + // An experimental skill is read from its repo_dir. + data, err = src.ReadFile(t.Context(), "beta", "SKILL.md") + require.NoError(t, err) + assert.Contains(t, string(data), "# Beta") +} + +func TestUnknownSkillAndFile(t *testing.T) { + src := fixtureSource() + + _, err := src.ReadFile(t.Context(), "missing", "SKILL.md") + assert.ErrorIs(t, err, ErrUnknownSkill) + + _, err = src.ReadFile(t.Context(), "alpha", "missing.md") + assert.ErrorIs(t, err, ErrUnknownFile) + + // A file of another skill is not a file of this one. + _, err = src.ReadFile(t.Context(), "beta", "references/guide.md") + assert.ErrorIs(t, err, ErrUnknownFile) +} + +func TestUnreachableSource(t *testing.T) { + src := NewFSSource(fstest.MapFS{}, "empty") + + _, err := src.Catalog(t.Context()) + assert.ErrorIs(t, err, ErrSourceUnreachable) + + _, err = src.ReadFile(t.Context(), "alpha", "SKILL.md") + assert.ErrorIs(t, err, ErrSourceUnreachable) +} + +func TestManifestPathsOutsideReleaseAreRejected(t *testing.T) { + for name, manifest := range map[string]string{ + "file outside the skill directory": `{"skills": {"alpha": {"files": ["../../secret"]}}}`, + "repo_dir outside the release": `{"skills": {"alpha": {"files": ["SKILL.md"], "repo_dir": "../other"}}}`, + "catalog_rules outside the release": `{"catalog_rules": "../RULES.md", "skills": {}}`, + } { + t.Run(name, func(t *testing.T) { + src := mapSource(manifest) + + _, err := src.Catalog(t.Context()) + assert.ErrorIs(t, err, ErrUnsafeManifestPath) + }) + } + + // A file the manifest names outside its skill is refused on read too. + _, err := mapSource(`{"skills": {"alpha": {"files": ["../../secret"]}}}`).ReadFile(t.Context(), "alpha", "../../secret") + assert.ErrorIs(t, err, ErrUnsafeManifestPath) +} + +func TestManifestUnknownFieldsAreIgnored(t *testing.T) { + src := mapSource(`{ + "version": "2.0.0", + "future_field": {"anything": true}, + "skills": {"alpha": {"files": ["SKILL.md"], "future_skill_field": 1}} + }`) + + catalog, err := src.Catalog(t.Context()) + require.NoError(t, err) + require.Len(t, catalog.Skills, 1) + assert.Equal(t, []string{"SKILL.md"}, catalog.Skills[0].Files) +} + +func TestManifestWithoutCommandsOrCatalogRules(t *testing.T) { + src := mapSource(`{"version": "1.0.0", "skills": {"alpha": {"files": ["SKILL.md"]}}}`) + + catalog, err := src.Catalog(t.Context()) + require.NoError(t, err) + assert.Empty(t, catalog.Rules) + require.Len(t, catalog.Skills, 1) + assert.Nil(t, catalog.Skills[0].Commands) +} diff --git a/libs/skills/manifest.go b/libs/skills/manifest.go new file mode 100644 index 00000000000..065608f2c14 --- /dev/null +++ b/libs/skills/manifest.go @@ -0,0 +1,118 @@ +package skills + +import ( + "errors" + "fmt" + "maps" + "slices" + "strings" +) + +const ( + // StableRepoDir is the release directory of stable skills (the repo_dir default). + StableRepoDir = "skills" + + // ExperimentalRepoDir is the release directory of experimental skills. + ExperimentalRepoDir = "experimental" + + // StateFileName is the install state file the installer keeps beside the + // skill directories. No skill may take this name. + StateFileName = ".state.json" +) + +// ErrUnsafeManifestPath reports a skills manifest that names a skill or file +// outside the skills directory. The command layer classifies it like a +// manifest that does not parse. +var ErrUnsafeManifestPath = errors.New("skills manifest names a path outside the skills directory") + +// Manifest describes the skills manifest fetched from the skills repo. +type Manifest struct { + Version string `json:"version"` + UpdatedAt string `json:"updated_at"` + Skills map[string]SkillMeta `json:"skills"` + + // CatalogRules names a file at the release root whose text the skills + // catalog shows above the skill list (manifest field catalog_rules). + CatalogRules string `json:"catalog_rules,omitempty"` +} + +// SkillMeta describes a single skill entry in the manifest. +type SkillMeta struct { + Version string `json:"version"` + UpdatedAt string `json:"updated_at"` + Files []string `json:"files"` + Description string `json:"description,omitempty"` + MinCLIVer string `json:"min_cli_version,omitempty"` + + // RepoDir is "skills" or "experimental" (manifest field repo_dir). + RepoDir string `json:"repo_dir,omitempty"` + + // Commands lists the CLI command groups the skill covers (manifest field commands). + Commands []string `json:"commands,omitempty"` + + // SourceName is the upstream skill directory name within RepoDir. + // Set during normalization, not from JSON. + SourceName string `json:"-"` +} + +// IsExperimental reports whether the skill lives in the experimental directory. +func (s SkillMeta) IsExperimental() bool { + return s.RepoDir == ExperimentalRepoDir +} + +// NormalizeManifest stamps SourceName and defaults RepoDir for older manifests. +func NormalizeManifest(m *Manifest) { + if m.Skills == nil { + m.Skills = map[string]SkillMeta{} + } + for name, meta := range m.Skills { + if meta.RepoDir == "" { + meta.RepoDir = StableRepoDir + } + meta.SourceName = name + m.Skills[name] = meta + } +} + +// CheckManifestPaths fails a manifest that names a skill or file outside its +// directory, or a skill named like the state file. The manifest comes from the +// network, so it must not be able to name ../../.bashrc, and only a broken or +// tampered manifest lists such an entry. The rule is the same on every OS. +// Entries that stay inside their directory but are not portable are left to +// the installer, which skips only that skill. +func CheckManifestPaths(m *Manifest) error { + for _, name := range slices.Sorted(maps.Keys(m.Skills)) { + if name == "" || name == "." || name == ".." || name == StateFileName || strings.ContainsAny(name, `/\`) { + return fmt.Errorf("%w: skill name %q", ErrUnsafeManifestPath, name) + } + for _, file := range m.Skills[name].Files { + if EscapesDir(file) { + return fmt.Errorf("%w: skill %q lists file %q", ErrUnsafeManifestPath, name, file) + } + } + } + return nil +} + +// EscapesDir reports whether file, joined onto a directory, names a path +// outside it on some OS: an absolute path, a Windows drive, or more ".." +// elements than the elements before them, with either slash as the separator. +func EscapesDir(file string) bool { + if strings.HasPrefix(file, "/") || strings.HasPrefix(file, `\`) || (len(file) >= 2 && file[1] == ':') { + return true + } + depth := 0 + for _, elem := range strings.FieldsFunc(file, func(r rune) bool { return r == '/' || r == '\\' }) { + switch elem { + case ".": + case "..": + depth-- + if depth < 0 { + return true + } + default: + depth++ + } + } + return false +} diff --git a/libs/skills/skills.go b/libs/skills/skills.go new file mode 100644 index 00000000000..1d87379c621 --- /dev/null +++ b/libs/skills/skills.go @@ -0,0 +1,60 @@ +// Package skills lists and reads Databricks skills from any source that serves +// a skills release: a published release, a bundled snapshot or a local folder. +package skills + +import ( + "context" + "errors" + "time" +) + +var ( + // ErrUnknownSkill reports a skill name the catalog does not list. + ErrUnknownSkill = errors.New("unknown skill") + + // ErrUnknownFile reports a file the catalog does not list for the skill. + ErrUnknownFile = errors.New("unknown skill file") + + // ErrSourceUnreachable reports a source whose release cannot be read. + ErrSourceUnreachable = errors.New("skills source unreachable") +) + +// Skill is one skill in a catalog. +type Skill struct { + Name string + Description string + Version string + + // Files lists the skill's files relative to the skill directory, SKILL.md included. + Files []string + + // Commands lists the CLI command groups the skill covers. + Commands []string + + Experimental bool +} + +// Catalog is the set of skills a source serves. +type Catalog struct { + // Skills are sorted by name. + Skills []Skill + + // Version is the release version. + Version string + + // Label says where the catalog came from. + Label string + + FetchedAt time.Time + Stale bool + + // Rules is text shown above the catalog, empty when the release has none. + Rules string +} + +// Source serves skills. Callers list skills and their files from the catalog, +// and read file contents with ReadFile. +type Source interface { + Catalog(ctx context.Context) (*Catalog, error) + ReadFile(ctx context.Context, skill, path string) ([]byte, error) +} diff --git a/libs/skills/testdata/release/RULES.md b/libs/skills/testdata/release/RULES.md new file mode 100644 index 00000000000..1015835d576 --- /dev/null +++ b/libs/skills/testdata/release/RULES.md @@ -0,0 +1 @@ +Use the catalog before you read a skill. diff --git a/libs/skills/testdata/release/experimental/beta/SKILL.md b/libs/skills/testdata/release/experimental/beta/SKILL.md new file mode 100644 index 00000000000..30a944da32e --- /dev/null +++ b/libs/skills/testdata/release/experimental/beta/SKILL.md @@ -0,0 +1,6 @@ +--- +name: beta +description: An experimental skill. +--- + +# Beta diff --git a/libs/skills/testdata/release/manifest.json b/libs/skills/testdata/release/manifest.json new file mode 100644 index 00000000000..b4ae3908658 --- /dev/null +++ b/libs/skills/testdata/release/manifest.json @@ -0,0 +1,8 @@ +{ + "version": "1.2.0", + "catalog_rules": "RULES.md", + "skills": { + "beta": {"version": "0.1.0", "description": "An experimental skill.", "files": ["SKILL.md"], "repo_dir": "experimental"}, + "alpha": {"version": "1.0.0", "description": "A stable skill with a nested file.", "files": ["SKILL.md", "references/guide.md"], "commands": ["jobs", "pipelines"], "repo_dir": "skills"} + } +} diff --git a/libs/skills/testdata/release/skills/alpha/SKILL.md b/libs/skills/testdata/release/skills/alpha/SKILL.md new file mode 100644 index 00000000000..aeaecf6bcea --- /dev/null +++ b/libs/skills/testdata/release/skills/alpha/SKILL.md @@ -0,0 +1,6 @@ +--- +name: alpha +description: A stable skill with a nested file. +--- + +# Alpha diff --git a/libs/skills/testdata/release/skills/alpha/references/guide.md b/libs/skills/testdata/release/skills/alpha/references/guide.md new file mode 100644 index 00000000000..0ab921f5810 --- /dev/null +++ b/libs/skills/testdata/release/skills/alpha/references/guide.md @@ -0,0 +1,3 @@ +# Guide + +Read this for details. From 2df5cf8642309fb63fc375fffa0d07fa9320f3e7 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Wed, 25 Nov 2026 18:56:48 +0000 Subject: [PATCH 02/25] Share the install state file name with libs/skills The installer and libs/skills both reserve .state.json. Define the name once in libs/skills and have the installer use it. Co-authored-by: Isaac --- libs/aitools/installer/state.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libs/aitools/installer/state.go b/libs/aitools/installer/state.go index 599cacab00b..0e0310e48f1 100644 --- a/libs/aitools/installer/state.go +++ b/libs/aitools/installer/state.go @@ -13,6 +13,7 @@ import ( "github.com/databricks/cli/libs/atomicfile" "github.com/databricks/cli/libs/env" + "github.com/databricks/cli/libs/skills" ) // clearFileRecords removes all file-provenance entries belonging to a skill @@ -27,7 +28,8 @@ func clearFileRecords(files map[string]FileRecord, skillName string) { } } -const stateFileName = ".state.json" +// stateFileName is the install state file; libs/skills reserves the same name. +const stateFileName = skills.StateFileName // CurrentSchemaVersion is the on-disk state schema version this CLI writes. v2 // added the Plugins and Files maps; v3 adds the optional MCP section. Older state From aa6b7d3148ba0784f48ec42e723641162e04b12b Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Wed, 25 Nov 2026 19:13:24 +0000 Subject: [PATCH 03/25] Compare skill fixtures with normalized line endings The Windows CI checkout turns the LF fixtures into CRLF, so the exact content assertions failed. Normalize line endings before comparing. Co-authored-by: Isaac --- libs/skills/fs_test.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/libs/skills/fs_test.go b/libs/skills/fs_test.go index 93426406fa5..c681f78acd9 100644 --- a/libs/skills/fs_test.go +++ b/libs/skills/fs_test.go @@ -2,6 +2,7 @@ package skills import ( "os" + "strings" "testing" "testing/fstest" @@ -13,6 +14,12 @@ func fixtureSource() Source { return NewFSSource(os.DirFS("testdata/release"), "test release") } +// lf normalizes line endings, so the fixtures compare equal on a checkout +// that turns LF into CRLF, as Windows does. +func lf(s string) string { + return strings.ReplaceAll(s, "\r\n", "\n") +} + func mapSource(manifest string) Source { return NewFSSource(fstest.MapFS{"manifest.json": {Data: []byte(manifest)}}, "map") } @@ -25,7 +32,7 @@ func TestCatalogFromFixture(t *testing.T) { assert.Equal(t, "test release", catalog.Label) assert.False(t, catalog.Stale) assert.False(t, catalog.FetchedAt.IsZero()) - assert.Equal(t, "Use the catalog before you read a skill.\n", catalog.Rules) + assert.Equal(t, "Use the catalog before you read a skill.\n", lf(catalog.Rules)) require.Len(t, catalog.Skills, 2) assert.Equal(t, Skill{ @@ -53,7 +60,7 @@ func TestReadFiles(t *testing.T) { data, err = src.ReadFile(t.Context(), "alpha", "references/guide.md") require.NoError(t, err) - assert.Equal(t, "# Guide\n\nRead this for details.\n", string(data)) + assert.Equal(t, "# Guide\n\nRead this for details.\n", lf(string(data))) // An experimental skill is read from its repo_dir. data, err = src.ReadFile(t.Context(), "beta", "SKILL.md") From fb7d076e2360bf204856aa558077c2915f4461cb Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Wed, 25 Nov 2026 19:55:11 +0000 Subject: [PATCH 04/25] Address review on the skills source Clean catalog_rules before reading it, expose min_cli_version on Skill, document the Catalog fields and the release-relative paths the manifest may name. Co-authored-by: Isaac --- libs/skills/fs.go | 18 ++++++++++++------ libs/skills/fs_test.go | 20 ++++++++++++++++++++ libs/skills/manifest.go | 9 +++++---- libs/skills/skills.go | 16 ++++++++++++++-- 4 files changed, 51 insertions(+), 12 deletions(-) diff --git a/libs/skills/fs.go b/libs/skills/fs.go index e3575915796..2718d9fc65b 100644 --- a/libs/skills/fs.go +++ b/libs/skills/fs.go @@ -40,12 +40,13 @@ func (s *fsSource) Catalog(_ context.Context) (*Catalog, error) { for _, name := range slices.Sorted(maps.Keys(m.Skills)) { meta := m.Skills[name] catalog.Skills = append(catalog.Skills, Skill{ - Name: name, - Description: meta.Description, - Version: meta.Version, - Files: meta.Files, - Commands: meta.Commands, - Experimental: meta.IsExperimental(), + Name: name, + Description: meta.Description, + Version: meta.Version, + Files: meta.Files, + Commands: meta.Commands, + MinCLIVersion: meta.MinCLIVer, + Experimental: meta.IsExperimental(), }) } return catalog, nil @@ -90,6 +91,11 @@ func (s *fsSource) manifest() (*Manifest, error) { return nil, fmt.Errorf("%w: skill %q has repo_dir %q", ErrUnsafeManifestPath, name, repoDir) } } + if m.CatalogRules != "" { + // Clean the path the way skill files are cleaned by path.Join, so that + // "./RULES.md" and "docs/../RULES.md" are read like "RULES.md". + m.CatalogRules = path.Clean(m.CatalogRules) + } if EscapesDir(m.CatalogRules) { return nil, fmt.Errorf("%w: catalog_rules %q", ErrUnsafeManifestPath, m.CatalogRules) } diff --git a/libs/skills/fs_test.go b/libs/skills/fs_test.go index c681f78acd9..e78cdef55c7 100644 --- a/libs/skills/fs_test.go +++ b/libs/skills/fs_test.go @@ -133,3 +133,23 @@ func TestManifestWithoutCommandsOrCatalogRules(t *testing.T) { require.Len(t, catalog.Skills, 1) assert.Nil(t, catalog.Skills[0].Commands) } + +func TestCatalogRulesPathIsCleaned(t *testing.T) { + for _, rules := range []string{"./RULES.md", "docs/../RULES.md"} { + src := NewFSSource(fstest.MapFS{ + "manifest.json": {Data: []byte(`{"catalog_rules": "` + rules + `", "skills": {}}`)}, + "RULES.md": {Data: []byte("rules")}, + }, "map") + + catalog, err := src.Catalog(t.Context()) + require.NoError(t, err, rules) + assert.Equal(t, "rules", catalog.Rules, rules) + } +} + +func TestManifestMinCLIVersionIsListed(t *testing.T) { + catalog, err := mapSource(`{"skills": {"alpha": {"files": ["SKILL.md"], "min_cli_version": "99.0.0"}}}`).Catalog(t.Context()) + require.NoError(t, err) + require.Len(t, catalog.Skills, 1) + assert.Equal(t, "99.0.0", catalog.Skills[0].MinCLIVersion) +} diff --git a/libs/skills/manifest.go b/libs/skills/manifest.go index 065608f2c14..a8b4c5a2d13 100644 --- a/libs/skills/manifest.go +++ b/libs/skills/manifest.go @@ -20,8 +20,9 @@ const ( StateFileName = ".state.json" ) -// ErrUnsafeManifestPath reports a skills manifest that names a skill or file -// outside the skills directory. The command layer classifies it like a +// ErrUnsafeManifestPath reports a skills manifest that names a skill directory, +// a skill file or catalog_rules outside the release. Its message keeps the +// wording install has always printed. The command layer classifies it like a // manifest that does not parse. var ErrUnsafeManifestPath = errors.New("skills manifest names a path outside the skills directory") @@ -31,8 +32,8 @@ type Manifest struct { UpdatedAt string `json:"updated_at"` Skills map[string]SkillMeta `json:"skills"` - // CatalogRules names a file at the release root whose text the skills - // catalog shows above the skill list (manifest field catalog_rules). + // CatalogRules names a file in the release, relative to its root, whose text + // the skills catalog shows above the skill list (manifest field catalog_rules). CatalogRules string `json:"catalog_rules,omitempty"` } diff --git a/libs/skills/skills.go b/libs/skills/skills.go index 1d87379c621..1247a40e944 100644 --- a/libs/skills/skills.go +++ b/libs/skills/skills.go @@ -31,12 +31,19 @@ type Skill struct { // Commands lists the CLI command groups the skill covers. Commands []string + // MinCLIVersion is the oldest CLI version that can use the skill (manifest + // field min_cli_version). Install skips the skill on an older CLI, so callers + // that install skills must apply the same check. + MinCLIVersion string + Experimental bool } // Catalog is the set of skills a source serves. type Catalog struct { - // Skills are sorted by name. + // Skills are sorted by name. The catalog lists every skill the release + // names. Install also skips a skill with a non-portable name or file path, + // and a skill whose MinCLIVersion is newer than the running CLI. Skills []Skill // Version is the release version. @@ -45,8 +52,13 @@ type Catalog struct { // Label says where the catalog came from. Label string + // FetchedAt is when the source produced the catalog. A source that serves + // a cached copy sets it to the time the copy was fetched. FetchedAt time.Time - Stale bool + + // Stale reports that the source served a cached copy it could not refresh. + // Sources that always read the release themselves leave it false. + Stale bool // Rules is text shown above the catalog, empty when the release has none. Rules string From c1365d3c1af48e2bb4f425d653856acd51be75ce Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Thu, 26 Nov 2026 09:00:22 +0000 Subject: [PATCH 05/25] Add the skills command group behind DATABRICKS_SKILLS_PREVIEW Register the hidden skills command group only when DATABRICKS_SKILLS_PREVIEW is set. Its five subcommands are stubs that report they are not implemented yet. Add guards for the feature and for its hints switch, DATABRICKS_SKILLS_HINTS, and a resolver for the folder in DATABRICKS_SKILLS_DIR, with an acceptance fixture release that later changes reuse. With the variable unset, the command group is not registered and nothing else changes. Co-authored-by: Isaac --- acceptance/cmd/skills/disabled/out.test.toml | 1 + acceptance/cmd/skills/disabled/output.txt | 5 ++ acceptance/cmd/skills/disabled/script | 3 + acceptance/cmd/skills/disabled/test.toml | 1 + acceptance/cmd/skills/enabled/out.test.toml | 1 + acceptance/cmd/skills/enabled/output.txt | 41 ++++++++++++ acceptance/cmd/skills/enabled/script | 10 +++ acceptance/cmd/skills/enabled/test.toml | 2 + acceptance/cmd/skills/release/manifest.json | 6 ++ .../skills/release/skills/demo-skill/SKILL.md | 6 ++ cmd/cmd.go | 5 ++ cmd/skills/list.go | 14 ++++ cmd/skills/list_files.go | 14 ++++ cmd/skills/read.go | 14 ++++ cmd/skills/read_file.go | 14 ++++ cmd/skills/search.go | 14 ++++ cmd/skills/skills.go | 33 ++++++++++ libs/skills/guard.go | 34 ++++++++++ libs/skills/guard_test.go | 64 +++++++++++++++++++ libs/skills/resolve.go | 40 ++++++++++++ libs/skills/resolve_test.go | 43 +++++++++++++ 21 files changed, 365 insertions(+) create mode 100644 acceptance/cmd/skills/disabled/out.test.toml create mode 100644 acceptance/cmd/skills/disabled/output.txt create mode 100644 acceptance/cmd/skills/disabled/script create mode 100644 acceptance/cmd/skills/disabled/test.toml create mode 100644 acceptance/cmd/skills/enabled/out.test.toml create mode 100644 acceptance/cmd/skills/enabled/output.txt create mode 100644 acceptance/cmd/skills/enabled/script create mode 100644 acceptance/cmd/skills/enabled/test.toml create mode 100644 acceptance/cmd/skills/release/manifest.json create mode 100644 acceptance/cmd/skills/release/skills/demo-skill/SKILL.md create mode 100644 cmd/skills/list.go create mode 100644 cmd/skills/list_files.go create mode 100644 cmd/skills/read.go create mode 100644 cmd/skills/read_file.go create mode 100644 cmd/skills/search.go create mode 100644 cmd/skills/skills.go create mode 100644 libs/skills/guard.go create mode 100644 libs/skills/guard_test.go create mode 100644 libs/skills/resolve.go create mode 100644 libs/skills/resolve_test.go diff --git a/acceptance/cmd/skills/disabled/out.test.toml b/acceptance/cmd/skills/disabled/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/skills/disabled/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/skills/disabled/output.txt b/acceptance/cmd/skills/disabled/output.txt new file mode 100644 index 00000000000..0c7e76db4aa --- /dev/null +++ b/acceptance/cmd/skills/disabled/output.txt @@ -0,0 +1,5 @@ + +>>> env -u DATABRICKS_SKILLS_PREVIEW [CLI] skills list +Error: unknown command "skills" for "databricks" + +>>> env -u DATABRICKS_SKILLS_PREVIEW [CLI] --help diff --git a/acceptance/cmd/skills/disabled/script b/acceptance/cmd/skills/disabled/script new file mode 100644 index 00000000000..f06f9b1b9fd --- /dev/null +++ b/acceptance/cmd/skills/disabled/script @@ -0,0 +1,3 @@ +# Unset, the skills group is not registered: it is an unknown command and is not listed in help. +musterr trace env -u DATABRICKS_SKILLS_PREVIEW $CLI skills list +trace env -u DATABRICKS_SKILLS_PREVIEW $CLI --help | contains.py "! skills " > /dev/null diff --git a/acceptance/cmd/skills/disabled/test.toml b/acceptance/cmd/skills/disabled/test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/skills/disabled/test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/skills/enabled/out.test.toml b/acceptance/cmd/skills/enabled/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/skills/enabled/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/skills/enabled/output.txt b/acceptance/cmd/skills/enabled/output.txt new file mode 100644 index 00000000000..f376535e2de --- /dev/null +++ b/acceptance/cmd/skills/enabled/output.txt @@ -0,0 +1,41 @@ + +>>> [CLI] skills --help +List, read and search Databricks skills + +Usage: + databricks skills [command] + +Available Commands: + list List the available skills + list-files List the files of a skill + read Read a skill's instructions + read-file Read one file of a skill + search Search the skills for words + +Flags: + -h, --help[=true|false] help for skills + +Global Flags: + --debug[=true|false] enable debug logging + -o, --output type output type: text or json (default text) + -p, --profile string ~/.databrickscfg profile + -t, --target string bundle target to use (if applicable) + +Use "databricks skills [command] --help" for more information about a command. + +>>> [CLI] --help + +>>> [CLI] skills list +Error: databricks skills list is not implemented yet + +>>> [CLI] skills read demo-skill +Error: databricks skills read is not implemented yet + +>>> [CLI] skills list-files demo-skill +Error: databricks skills list-files is not implemented yet + +>>> [CLI] skills read-file demo-skill SKILL.md +Error: databricks skills read-file is not implemented yet + +>>> [CLI] skills search skill words +Error: databricks skills search is not implemented yet diff --git a/acceptance/cmd/skills/enabled/script b/acceptance/cmd/skills/enabled/script new file mode 100644 index 00000000000..ebd3804ae95 --- /dev/null +++ b/acceptance/cmd/skills/enabled/script @@ -0,0 +1,10 @@ +# With the variable set, the group lists its five subcommands and stays hidden from the root help. +trace $CLI skills --help +trace $CLI --help | contains.py "! skills " > /dev/null + +# Each subcommand is a stub that exits non-zero with the not-implemented message. +musterr trace $CLI skills list +musterr trace $CLI skills read demo-skill +musterr trace $CLI skills list-files demo-skill +musterr trace $CLI skills read-file demo-skill SKILL.md +musterr trace $CLI skills search skill words diff --git a/acceptance/cmd/skills/enabled/test.toml b/acceptance/cmd/skills/enabled/test.toml new file mode 100644 index 00000000000..27401a415e2 --- /dev/null +++ b/acceptance/cmd/skills/enabled/test.toml @@ -0,0 +1,2 @@ +Cloud = false +Env.DATABRICKS_SKILLS_PREVIEW = "1" diff --git a/acceptance/cmd/skills/release/manifest.json b/acceptance/cmd/skills/release/manifest.json new file mode 100644 index 00000000000..fe67500f60a --- /dev/null +++ b/acceptance/cmd/skills/release/manifest.json @@ -0,0 +1,6 @@ +{ + "version": "0.0.1", + "skills": { + "demo-skill": {"version": "0.0.1", "description": "A skill for tests.", "files": ["SKILL.md"]} + } +} diff --git a/acceptance/cmd/skills/release/skills/demo-skill/SKILL.md b/acceptance/cmd/skills/release/skills/demo-skill/SKILL.md new file mode 100644 index 00000000000..47cd5d23ccd --- /dev/null +++ b/acceptance/cmd/skills/release/skills/demo-skill/SKILL.md @@ -0,0 +1,6 @@ +--- +name: demo-skill +description: A skill for tests. +--- + +# Demo skill diff --git a/cmd/cmd.go b/cmd/cmd.go index 2a987c114b4..4f24d2474ad 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -26,10 +26,12 @@ import ( "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/cmd/sandbox" "github.com/databricks/cli/cmd/selftest" + skillscmd "github.com/databricks/cli/cmd/skills" "github.com/databricks/cli/cmd/sync" "github.com/databricks/cli/cmd/version" "github.com/databricks/cli/cmd/workspace" "github.com/databricks/cli/libs/cmdgroup" + "github.com/databricks/cli/libs/skills" "github.com/spf13/cobra" ) @@ -82,6 +84,9 @@ func workspaceSpec(spec root.CommandSpec) root.CommandSpec { func New(ctx context.Context) *root.Tree { cli := root.NewTree(ctx) cli.Add(topLevelSpecs()...) + if skills.Enabled(ctx) { + cli.Add(skillscmd.Spec) + } // Add workspace command groups, filtering out empty groups or groups with only hidden commands. cli.AddGroups(append(workspace.Groups(), cobra.Group{ diff --git a/cmd/skills/list.go b/cmd/skills/list.go new file mode 100644 index 00000000000..8d4d116d87a --- /dev/null +++ b/cmd/skills/list.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newListCmd() *cobra.Command { + return &cobra.Command{ + Use: "list", + Short: "List the available skills", + Args: cobra.NoArgs, + RunE: notImplemented, + } +} diff --git a/cmd/skills/list_files.go b/cmd/skills/list_files.go new file mode 100644 index 00000000000..016d2cecfe0 --- /dev/null +++ b/cmd/skills/list_files.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newListFilesCmd() *cobra.Command { + return &cobra.Command{ + Use: "list-files ", + Short: "List the files of a skill", + Args: cobra.ExactArgs(1), + RunE: notImplemented, + } +} diff --git a/cmd/skills/read.go b/cmd/skills/read.go new file mode 100644 index 00000000000..2bf7814e55f --- /dev/null +++ b/cmd/skills/read.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newReadCmd() *cobra.Command { + return &cobra.Command{ + Use: "read ", + Short: "Read a skill's instructions", + Args: cobra.ExactArgs(1), + RunE: notImplemented, + } +} diff --git a/cmd/skills/read_file.go b/cmd/skills/read_file.go new file mode 100644 index 00000000000..e6172eb0d2b --- /dev/null +++ b/cmd/skills/read_file.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newReadFileCmd() *cobra.Command { + return &cobra.Command{ + Use: "read-file ", + Short: "Read one file of a skill", + Args: cobra.ExactArgs(2), + RunE: notImplemented, + } +} diff --git a/cmd/skills/search.go b/cmd/skills/search.go new file mode 100644 index 00000000000..e46451e2bdb --- /dev/null +++ b/cmd/skills/search.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newSearchCmd() *cobra.Command { + return &cobra.Command{ + Use: "search ", + Short: "Search the skills for words", + Args: cobra.MinimumNArgs(1), + RunE: notImplemented, + } +} diff --git a/cmd/skills/skills.go b/cmd/skills/skills.go new file mode 100644 index 00000000000..963add4ee16 --- /dev/null +++ b/cmd/skills/skills.go @@ -0,0 +1,33 @@ +// Package skills implements the `databricks skills` command group. The group +// is registered only when libs/skills.Enabled is true, and is hidden from help. +package skills + +import ( + "context" + "fmt" + + "github.com/databricks/cli/cmd/root" + "github.com/spf13/cobra" +) + +// Spec declares the skills command group. +var Spec = root.CommandSpec{ + Use: "skills", + Short: "List, read and search Databricks skills", + Hidden: true, + Build: buildCommand, +} + +func buildCommand(_ context.Context, cmd *cobra.Command) { + cmd.AddCommand(newListCmd()) + cmd.AddCommand(newReadCmd()) + cmd.AddCommand(newListFilesCmd()) + cmd.AddCommand(newReadFileCmd()) + cmd.AddCommand(newSearchCmd()) +} + +// notImplemented is the run function of every subcommand until its own change +// lands. +func notImplemented(cmd *cobra.Command, _ []string) error { + return fmt.Errorf("%s is not implemented yet", cmd.CommandPath()) +} diff --git a/libs/skills/guard.go b/libs/skills/guard.go new file mode 100644 index 00000000000..dc3182dfabf --- /dev/null +++ b/libs/skills/guard.go @@ -0,0 +1,34 @@ +package skills + +import ( + "context" + + "github.com/databricks/cli/libs/env" +) + +const ( + // previewEnv turns the skills feature on. Off, the skills command group is + // not registered and nothing else in the feature runs. + previewEnv = "DATABRICKS_SKILLS_PREVIEW" + + // hintsEnv turns on skill hints. It only has an effect while previewEnv is set. + hintsEnv = "DATABRICKS_SKILLS_HINTS" +) + +// Enabled reports whether the skills feature is on. It is the gate for the +// whole feature: unless DATABRICKS_SKILLS_PREVIEW is set to a true value, the +// skills command group is not registered. +func Enabled(ctx context.Context) bool { + return envTrue(ctx, previewEnv) +} + +// HintsEnabled reports whether skill hints are on. Hints need the feature on +// and DATABRICKS_SKILLS_HINTS set to a true value of their own. +func HintsEnabled(ctx context.Context) bool { + return Enabled(ctx) && envTrue(ctx, hintsEnv) +} + +func envTrue(ctx context.Context, key string) bool { + on, _ := env.GetBool(ctx, key) + return on +} diff --git a/libs/skills/guard_test.go b/libs/skills/guard_test.go new file mode 100644 index 00000000000..6d0950df76a --- /dev/null +++ b/libs/skills/guard_test.go @@ -0,0 +1,64 @@ +package skills + +import ( + "testing" + + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" +) + +func TestEnabled(t *testing.T) { + cases := []struct { + name string + value string + set bool + want bool + }{ + {name: "unset", want: false}, + {name: "true", set: true, value: "true", want: true}, + {name: "one", set: true, value: "1", want: true}, + {name: "false", set: true, value: "false", want: false}, + {name: "zero", set: true, value: "0", want: false}, + {name: "empty", set: true, value: "", want: false}, + {name: "invalid", set: true, value: "maybe", want: false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + ctx := t.Context() + if c.set { + ctx = env.Set(ctx, "DATABRICKS_SKILLS_PREVIEW", c.value) + } + assert.Equal(t, c.want, Enabled(ctx)) + }) + } +} + +func TestHintsEnabled(t *testing.T) { + cases := []struct { + name string + preview string + hints string + want bool + }{ + {name: "both unset", want: false}, + {name: "preview off, hints on", preview: "false", hints: "true", want: false}, + {name: "preview unset, hints on", hints: "true", want: false}, + {name: "preview on, hints unset", preview: "true", want: false}, + {name: "preview on, hints false", preview: "true", hints: "false", want: false}, + {name: "preview on, hints invalid", preview: "true", hints: "maybe", want: false}, + {name: "preview on, hints true", preview: "true", hints: "true", want: true}, + {name: "preview on, hints one", preview: "1", hints: "1", want: true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + ctx := t.Context() + if c.preview != "" { + ctx = env.Set(ctx, "DATABRICKS_SKILLS_PREVIEW", c.preview) + } + if c.hints != "" { + ctx = env.Set(ctx, "DATABRICKS_SKILLS_HINTS", c.hints) + } + assert.Equal(t, c.want, HintsEnabled(ctx)) + }) + } +} diff --git a/libs/skills/resolve.go b/libs/skills/resolve.go new file mode 100644 index 00000000000..44d23dde366 --- /dev/null +++ b/libs/skills/resolve.go @@ -0,0 +1,40 @@ +package skills + +import ( + "context" + "errors" + "os" + + "github.com/databricks/cli/libs/env" +) + +// dirEnv names a folder that holds a skills release. It is read before any +// other source, so a developer can point the CLI at a local copy. +const dirEnv = "DATABRICKS_SKILLS_DIR" + +// ErrNoSource reports that this build has no skills source to read from. +var ErrNoSource = errors.New("no skills source is available in this build") + +// Resolve returns the source that serves skills. For now that is the folder in +// DATABRICKS_SKILLS_DIR, when it is set. Otherwise no source is available. +func Resolve(ctx context.Context) (Source, error) { + dir := env.Get(ctx, dirEnv) + if dir == "" { + return nil, ErrNoSource + } + return NewFSSource(os.DirFS(dir), dir), nil +} + +// LocalCatalog returns the freshest catalog that needs no network call. For now +// that is the folder in DATABRICKS_SKILLS_DIR. It returns nil when no folder is +// set. +func LocalCatalog(ctx context.Context) (*Catalog, error) { + if env.Get(ctx, dirEnv) == "" { + return nil, nil + } + src, err := Resolve(ctx) + if err != nil { + return nil, err + } + return src.Catalog(ctx) +} diff --git a/libs/skills/resolve_test.go b/libs/skills/resolve_test.go new file mode 100644 index 00000000000..ee6641db46a --- /dev/null +++ b/libs/skills/resolve_test.go @@ -0,0 +1,43 @@ +package skills + +import ( + "path/filepath" + "testing" + + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestResolveWithoutDir(t *testing.T) { + src, err := Resolve(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", "")) + assert.ErrorIs(t, err, ErrNoSource) + assert.Nil(t, src) +} + +func TestResolveWithDir(t *testing.T) { + ctx := env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", "testdata/release") + src, err := Resolve(ctx) + require.NoError(t, err) + + catalog, err := src.Catalog(ctx) + require.NoError(t, err) + assert.Equal(t, "1.2.0", catalog.Version) + assert.Equal(t, "testdata/release", catalog.Label) +} + +func TestLocalCatalogWithoutDir(t *testing.T) { + catalog, err := LocalCatalog(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", "")) + assert.NoError(t, err) + assert.Nil(t, catalog) +} + +// The acceptance fixture is the release that later acceptance tests point +// DATABRICKS_SKILLS_DIR at, so this checks that it stays a valid release. +func TestLocalCatalogFromAcceptanceFixture(t *testing.T) { + dir := filepath.Join("..", "..", "acceptance", "cmd", "skills", "release") + catalog, err := LocalCatalog(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", dir)) + require.NoError(t, err) + require.Len(t, catalog.Skills, 1) + assert.Equal(t, "demo-skill", catalog.Skills[0].Name) +} From b2a2be65ecb22ac21f0c0969448ac14453c689c1 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Thu, 26 Nov 2026 09:11:12 +0000 Subject: [PATCH 06/25] Print the skills catalog from skills list The text output shows the catalog rules, one line per skill and a line on how to read a skill. Descriptions are cut at a word boundary to the widest width that keeps the output under a fixed budget, and only names are printed when the names alone do not fit. The JSON output carries the full catalog. Experimental skills are listed only with --experimental. A stale catalog prints a provenance line on stderr. The shared release fixture gains a catalog rules file and an experimental skill. Co-authored-by: Isaac --- acceptance/cmd/skills/enabled/output.txt | 3 - acceptance/cmd/skills/enabled/script | 3 +- acceptance/cmd/skills/list/out.test.toml | 1 + acceptance/cmd/skills/list/output.txt | 62 ++++++ acceptance/cmd/skills/list/script | 11 + acceptance/cmd/skills/list/test.toml | 2 + acceptance/cmd/skills/release/RULES.md | 2 + .../experimental/preview-skill/SKILL.md | 6 + acceptance/cmd/skills/release/manifest.json | 4 +- cmd/skills/list.go | 176 +++++++++++++++- cmd/skills/list_test.go | 190 ++++++++++++++++++ libs/skills/resolve_test.go | 3 +- 12 files changed, 454 insertions(+), 9 deletions(-) create mode 100644 acceptance/cmd/skills/list/out.test.toml create mode 100644 acceptance/cmd/skills/list/output.txt create mode 100644 acceptance/cmd/skills/list/script create mode 100644 acceptance/cmd/skills/list/test.toml create mode 100644 acceptance/cmd/skills/release/RULES.md create mode 100644 acceptance/cmd/skills/release/experimental/preview-skill/SKILL.md create mode 100644 cmd/skills/list_test.go diff --git a/acceptance/cmd/skills/enabled/output.txt b/acceptance/cmd/skills/enabled/output.txt index f376535e2de..f8be4b00706 100644 --- a/acceptance/cmd/skills/enabled/output.txt +++ b/acceptance/cmd/skills/enabled/output.txt @@ -25,9 +25,6 @@ Use "databricks skills [command] --help" for more information about a command. >>> [CLI] --help ->>> [CLI] skills list -Error: databricks skills list is not implemented yet - >>> [CLI] skills read demo-skill Error: databricks skills read is not implemented yet diff --git a/acceptance/cmd/skills/enabled/script b/acceptance/cmd/skills/enabled/script index ebd3804ae95..725ee04e047 100644 --- a/acceptance/cmd/skills/enabled/script +++ b/acceptance/cmd/skills/enabled/script @@ -2,8 +2,7 @@ trace $CLI skills --help trace $CLI --help | contains.py "! skills " > /dev/null -# Each subcommand is a stub that exits non-zero with the not-implemented message. -musterr trace $CLI skills list +# Each subcommand other than list is a stub that exits non-zero with the not-implemented message. musterr trace $CLI skills read demo-skill musterr trace $CLI skills list-files demo-skill musterr trace $CLI skills read-file demo-skill SKILL.md diff --git a/acceptance/cmd/skills/list/out.test.toml b/acceptance/cmd/skills/list/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/skills/list/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/skills/list/output.txt b/acceptance/cmd/skills/list/output.txt new file mode 100644 index 00000000000..1eef79d126c --- /dev/null +++ b/acceptance/cmd/skills/list/output.txt @@ -0,0 +1,62 @@ + +>>> [CLI] skills list +Pick the skill whose description matches the task. +Read the skill before you act on it. + +demo-skill: A skill for tests. +To read a skill, run: databricks skills read + +>>> [CLI] skills list --experimental +Pick the skill whose description matches the task. +Read the skill before you act on it. + +demo-skill: A skill for tests. +preview-skill: An experimental skill for tests. +To read a skill, run: databricks skills read + +>>> [CLI] skills list --output json +{ + "source": "[TESTROOT]/cmd/skills/release", + "release_version": "0.0.1", + "skills": [ + { + "name": "demo-skill", + "description": "A skill for tests.", + "version": "0.0.1", + "files": [ + "SKILL.md" + ], + "commands": [ + "jobs" + ] + } + ] +} + +>>> [CLI] skills list --output json --experimental +{ + "source": "[TESTROOT]/cmd/skills/release", + "release_version": "0.0.1", + "skills": [ + { + "name": "demo-skill", + "description": "A skill for tests.", + "version": "0.0.1", + "files": [ + "SKILL.md" + ], + "commands": [ + "jobs" + ] + }, + { + "name": "preview-skill", + "description": "An experimental skill for tests.", + "version": "0.0.2", + "files": [ + "SKILL.md" + ], + "commands": null + } + ] +} diff --git a/acceptance/cmd/skills/list/script b/acceptance/cmd/skills/list/script new file mode 100644 index 00000000000..6eae631818c --- /dev/null +++ b/acceptance/cmd/skills/list/script @@ -0,0 +1,11 @@ +export DATABRICKS_SKILLS_DIR=$TESTROOT/cmd/skills/release + +# Text: the catalog rules, then the stable skills by name, then how to read a skill. +trace $CLI skills list + +# Experimental skills are listed only with --experimental. +trace $CLI skills list --experimental + +# JSON: the full catalog, with the release version and source. +trace $CLI skills list --output json +trace $CLI skills list --output json --experimental diff --git a/acceptance/cmd/skills/list/test.toml b/acceptance/cmd/skills/list/test.toml new file mode 100644 index 00000000000..27401a415e2 --- /dev/null +++ b/acceptance/cmd/skills/list/test.toml @@ -0,0 +1,2 @@ +Cloud = false +Env.DATABRICKS_SKILLS_PREVIEW = "1" diff --git a/acceptance/cmd/skills/release/RULES.md b/acceptance/cmd/skills/release/RULES.md new file mode 100644 index 00000000000..2c8d6da3b4b --- /dev/null +++ b/acceptance/cmd/skills/release/RULES.md @@ -0,0 +1,2 @@ +Pick the skill whose description matches the task. +Read the skill before you act on it. diff --git a/acceptance/cmd/skills/release/experimental/preview-skill/SKILL.md b/acceptance/cmd/skills/release/experimental/preview-skill/SKILL.md new file mode 100644 index 00000000000..bf150c1bc4a --- /dev/null +++ b/acceptance/cmd/skills/release/experimental/preview-skill/SKILL.md @@ -0,0 +1,6 @@ +--- +name: preview-skill +description: An experimental skill for tests. +--- + +# Preview skill diff --git a/acceptance/cmd/skills/release/manifest.json b/acceptance/cmd/skills/release/manifest.json index fe67500f60a..0555786d3c9 100644 --- a/acceptance/cmd/skills/release/manifest.json +++ b/acceptance/cmd/skills/release/manifest.json @@ -1,6 +1,8 @@ { "version": "0.0.1", + "catalog_rules": "RULES.md", "skills": { - "demo-skill": {"version": "0.0.1", "description": "A skill for tests.", "files": ["SKILL.md"]} + "demo-skill": {"version": "0.0.1", "description": "A skill for tests.", "files": ["SKILL.md"], "commands": ["jobs"]}, + "preview-skill": {"version": "0.0.2", "description": "An experimental skill for tests.", "files": ["SKILL.md"], "repo_dir": "experimental"} } } diff --git a/cmd/skills/list.go b/cmd/skills/list.go index 8d4d116d87a..30c40069490 100644 --- a/cmd/skills/list.go +++ b/cmd/skills/list.go @@ -1,14 +1,186 @@ package skills import ( + "encoding/json" + "fmt" + "io" + "slices" + "strings" + "time" + + "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/flags" + libskills "github.com/databricks/cli/libs/skills" "github.com/spf13/cobra" ) +// textBudget is the most characters the text output of `skills list` may have. +// Descriptions are cut to fit it, so an agent sees the whole catalog at once. +const textBudget = 4000 + +const ( + readHint = "To read a skill, run: databricks skills read " + searchHint = "Descriptions are left out to fit the output. To find a skill, run: databricks skills search " +) + func newListCmd() *cobra.Command { - return &cobra.Command{ + var experimental bool + cmd := &cobra.Command{ Use: "list", Short: "List the available skills", Args: cobra.NoArgs, - RunE: notImplemented, + RunE: func(cmd *cobra.Command, _ []string) error { + src, err := libskills.Resolve(cmd.Context()) + if err != nil { + return err + } + return runList(cmd, src, experimental) + }, + } + cmd.Flags().BoolVar(&experimental, "experimental", false, "Include experimental skills") + return cmd +} + +func runList(cmd *cobra.Command, src libskills.Source, experimental bool) error { + catalog, err := src.Catalog(cmd.Context()) + if err != nil { + return err + } + if catalog.Stale { + fmt.Fprintln(cmd.ErrOrStderr(), provenanceLine(catalog)) + } + + list := visibleSkills(catalog.Skills, experimental) + if root.OutputType(cmd) == flags.OutputJSON { + return writeListJSON(cmd.OutOrStdout(), catalog, list) + } + _, err = io.WriteString(cmd.OutOrStdout(), renderText(catalog.Rules, list)) + return err +} + +// visibleSkills returns the skills to list, sorted by name so that the order +// is the same on every run. Experimental skills are left out unless asked for. +func visibleSkills(all []libskills.Skill, experimental bool) []libskills.Skill { + var list []libskills.Skill + for _, s := range all { + if s.Experimental && !experimental { + continue + } + list = append(list, s) + } + slices.SortFunc(list, func(a, b libskills.Skill) int { + return strings.Compare(a.Name, b.Name) + }) + return list +} + +func provenanceLine(catalog *libskills.Catalog) string { + return fmt.Sprintf("Skills come from %s (release %s, fetched %s). The source could not be refreshed, so the list may be out of date.", + catalog.Label, catalog.Version, catalog.FetchedAt.Format(time.RFC3339)) +} + +// renderText returns the text output of `skills list`: the catalog rules, then +// one line per skill, then a line on how to read a skill. When the whole output +// is over textBudget, descriptions are cut at a word boundary to the widest +// width that fits. When even the names do not fit, only the names are printed. +func renderText(rules string, list []libskills.Skill) string { + if len(list) == 0 { + return withRules(rules) + "No skills found.\n" + } + maxLen := 0 + for _, s := range list { + maxLen = max(maxLen, len(s.Description)) + } + if full := layoutText(rules, list, maxLen); len(full) <= textBudget { + return full + } + // Find the widest width in [0, maxLen-1] that fits. Width 0 lists names only. + lo, hi := 0, maxLen-1 + for lo < hi { + mid := (lo + hi + 1) / 2 + if len(layoutText(rules, list, mid)) <= textBudget { + lo = mid + } else { + hi = mid - 1 + } + } + return layoutText(rules, list, lo) +} + +// layoutText lays out the text output with descriptions cut to width. A width +// of 0 leaves the descriptions out. +func layoutText(rules string, list []libskills.Skill, width int) string { + var b strings.Builder + b.WriteString(withRules(rules)) + for _, s := range list { + switch { + case width == 0: + b.WriteString(s.Name + "\n") + case s.Description == "": + b.WriteString(s.Name + "\n") + default: + fmt.Fprintf(&b, "%s: %s\n", s.Name, cutWords(s.Description, width)) + } + } + if width == 0 { + b.WriteString(searchHint + "\n") + } + b.WriteString(readHint + "\n") + return b.String() +} + +func withRules(rules string) string { + rules = strings.TrimSpace(rules) + if rules == "" { + return "" + } + return rules + "\n\n" +} + +// cutWords returns desc unchanged when it fits in width. Otherwise it cuts desc +// at the last word boundary that leaves room for "..." within width. +func cutWords(desc string, width int) string { + if len(desc) <= width { + return desc + } + for i := min(width-3, len(desc)-1); i > 0; i-- { + if desc[i] == ' ' { + return desc[:i] + "..." + } + } + return "..." +} + +type listJSON struct { + Source string `json:"source"` + ReleaseVersion string `json:"release_version"` + Skills []listJSONSkill `json:"skills"` +} + +type listJSONSkill struct { + Name string `json:"name"` + Description string `json:"description"` + Version string `json:"version"` + Files []string `json:"files"` + Commands []string `json:"commands"` +} + +func writeListJSON(w io.Writer, catalog *libskills.Catalog, list []libskills.Skill) error { + out := listJSON{ + Source: catalog.Label, + ReleaseVersion: catalog.Version, + Skills: make([]listJSONSkill, 0, len(list)), + } + for _, s := range list { + out.Skills = append(out.Skills, listJSONSkill{ + Name: s.Name, + Description: s.Description, + Version: s.Version, + Files: s.Files, + Commands: s.Commands, + }) } + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(out) } diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go new file mode 100644 index 00000000000..01e34682e11 --- /dev/null +++ b/cmd/skills/list_test.go @@ -0,0 +1,190 @@ +package skills + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "strings" + "testing" + "time" + + "github.com/databricks/cli/libs/flags" + libskills "github.com/databricks/cli/libs/skills" + "github.com/spf13/cobra" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type fakeSource struct { + catalog *libskills.Catalog +} + +func (f fakeSource) Catalog(context.Context) (*libskills.Catalog, error) { + return f.catalog, nil +} + +func (f fakeSource) ReadFile(context.Context, string, string) ([]byte, error) { + return nil, libskills.ErrUnknownFile +} + +func listTestCmd(t *testing.T, output flags.Output) (*cobra.Command, *bytes.Buffer, *bytes.Buffer) { + t.Helper() + cmd := &cobra.Command{} + cmd.SetContext(t.Context()) + out := output + cmd.Flags().Var(&out, "output", "") + var stdout, stderr bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetErr(&stderr) + return cmd, &stdout, &stderr +} + +// longSkills returns n skills whose descriptions are far longer than the budget +// allows for each one. +func longSkills(n int) []libskills.Skill { + var list []libskills.Skill + for i := range n { + desc := strings.TrimSpace(strings.Repeat(fmt.Sprintf("word%d describes the skill in detail. ", i), 12)) + list = append(list, libskills.Skill{Name: fmt.Sprintf("skill-%02d", i), Description: desc}) + } + return list +} + +func TestRenderTextFortySkillsFitsBudget(t *testing.T) { + list := visibleSkills(longSkills(40), false) + require.Len(t, list, 40) + + out := renderText("Pick the skill whose description matches the task.", list) + + assert.LessOrEqual(t, len(out), textBudget) + for _, s := range list { + assert.Contains(t, out, s.Name+": ") + } + assert.True(t, strings.HasPrefix(out, "Pick the skill whose description matches the task.\n\n")) + assert.True(t, strings.HasSuffix(out, readHint+"\n")) + assert.NotContains(t, out, "databricks skills search") +} + +func TestRenderTextKeepsFullDescriptionsWhenTheyFit(t *testing.T) { + list := []libskills.Skill{ + {Name: "alpha", Description: "Alpha does one thing well."}, + {Name: "beta", Description: "Beta does another."}, + } + out := renderText("", list) + assert.Equal(t, "alpha: Alpha does one thing well.\nbeta: Beta does another.\n"+readHint+"\n", out) +} + +func TestRenderTextNamesOnlyWhenNamesExceedBudget(t *testing.T) { + var list []libskills.Skill + for i := range 400 { + list = append(list, libskills.Skill{ + Name: fmt.Sprintf("a-rather-long-skill-name-%03d", i), + Description: "Short.", + }) + } + out := renderText("", visibleSkills(list, false)) + + assert.Contains(t, out, "a-rather-long-skill-name-000\n") + assert.Contains(t, out, "a-rather-long-skill-name-399\n") + assert.NotContains(t, out, "Short.") + assert.Contains(t, out, "databricks skills search ") + assert.Contains(t, out, readHint) +} + +func TestRenderTextNoSkills(t *testing.T) { + assert.Equal(t, "No skills found.\n", renderText("", nil)) +} + +func TestCutWords(t *testing.T) { + tests := []struct { + desc string + width int + want string + }{ + {"short text", 20, "short text"}, + {"Hello world again", 12, "Hello..."}, + {"Hello world again", 11, "Hello..."}, + {"Hello world again", 9, "Hello..."}, + {"Hello world again", 8, "Hello..."}, + {"Hello world again", 7, "..."}, + {"Unbreakable", 6, "..."}, + } + for _, tt := range tests { + assert.Equal(t, tt.want, cutWords(tt.desc, tt.width), "cutWords(%q, %d)", tt.desc, tt.width) + } +} + +func TestVisibleSkillsSortsAndHidesExperimental(t *testing.T) { + all := []libskills.Skill{ + {Name: "zeta"}, + {Name: "preview", Experimental: true}, + {Name: "alpha"}, + } + + stable := visibleSkills(all, false) + assert.Equal(t, []string{"alpha", "zeta"}, names(stable)) + + withExperimental := visibleSkills(all, true) + assert.Equal(t, []string{"alpha", "preview", "zeta"}, names(withExperimental)) +} + +func TestRunListTextAndJSON(t *testing.T) { + catalog := &libskills.Catalog{ + Label: "test", + Version: "1.2.3", + FetchedAt: time.Now(), + Skills: []libskills.Skill{ + {Name: "beta", Description: "Second.", Version: "0.1", Files: []string{"SKILL.md"}, Commands: []string{"jobs"}}, + {Name: "alpha", Description: "First.", Version: "0.2", Files: []string{"SKILL.md"}}, + }, + } + + cmd, stdout, stderr := listTestCmd(t, flags.OutputText) + require.NoError(t, runList(cmd, fakeSource{catalog}, false)) + assert.Equal(t, "alpha: First.\nbeta: Second.\n"+readHint+"\n", stdout.String()) + assert.Empty(t, stderr.String()) + + cmd, stdout, _ = listTestCmd(t, flags.OutputJSON) + require.NoError(t, runList(cmd, fakeSource{catalog}, false)) + var got struct { + Source string `json:"source"` + ReleaseVersion string `json:"release_version"` + Skills []struct { + Name string `json:"name"` + Version string `json:"version"` + Files []string `json:"files"` + Commands []string `json:"commands"` + } `json:"skills"` + } + require.NoError(t, json.Unmarshal(stdout.Bytes(), &got)) + assert.Equal(t, "test", got.Source) + assert.Equal(t, "1.2.3", got.ReleaseVersion) + require.Len(t, got.Skills, 2) + assert.Equal(t, "alpha", got.Skills[0].Name) + assert.Equal(t, "beta", got.Skills[1].Name) + assert.Equal(t, []string{"jobs"}, got.Skills[1].Commands) +} + +func TestRunListStaleCatalogPrintsProvenanceOnStderr(t *testing.T) { + catalog := &libskills.Catalog{ + Label: "cached", + Version: "1.2.3", + FetchedAt: time.Date(2026, 11, 1, 0, 0, 0, 0, time.UTC), + Stale: true, + Skills: []libskills.Skill{{Name: "alpha", Description: "First."}}, + } + + cmd, stdout, stderr := listTestCmd(t, flags.OutputText) + require.NoError(t, runList(cmd, fakeSource{catalog}, false)) + assert.Contains(t, stderr.String(), "Skills come from cached (release 1.2.3, fetched 2026-11-01T00:00:00Z)") + assert.NotContains(t, stdout.String(), "Skills come from") +} + +func names(list []libskills.Skill) []string { + var out []string + for _, s := range list { + out = append(out, s.Name) + } + return out +} diff --git a/libs/skills/resolve_test.go b/libs/skills/resolve_test.go index ee6641db46a..fa09ff803d7 100644 --- a/libs/skills/resolve_test.go +++ b/libs/skills/resolve_test.go @@ -38,6 +38,7 @@ func TestLocalCatalogFromAcceptanceFixture(t *testing.T) { dir := filepath.Join("..", "..", "acceptance", "cmd", "skills", "release") catalog, err := LocalCatalog(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", dir)) require.NoError(t, err) - require.Len(t, catalog.Skills, 1) + require.Len(t, catalog.Skills, 2) assert.Equal(t, "demo-skill", catalog.Skills[0].Name) + assert.Equal(t, "preview-skill", catalog.Skills[1].Name) } From 055acad3664ef30a68544f5d33c3eafcc8af5a61 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Wed, 25 Nov 2026 18:43:24 +0000 Subject: [PATCH 07/25] Add a skills source interface over fs.FS Skill sources need the manifest type and its path checks, and the libs-no-aitools lint rule keeps shared libs from importing the installer. Move Manifest, SkillMeta, NormalizeManifest, CheckManifestPaths, EscapesDir and ErrUnsafeManifestPath down into libs/skills; the installer uses them from there through aliases. Add the Skill and Catalog types, the Source interface, sentinel errors, and NewFSSource over any fs.FS laid out like a skills release. The manifest accepts optional per-skill commands and a top-level catalog_rules file. Co-authored-by: Isaac --- libs/aitools/installer/errors.go | 3 +- libs/aitools/installer/installer.go | 38 ++---- libs/aitools/installer/installer_test.go | 3 +- libs/aitools/installer/source.go | 62 +-------- libs/aitools/installer/source_test.go | 13 +- libs/skills/fs.go | 97 +++++++++++++ libs/skills/fs_test.go | 128 ++++++++++++++++++ libs/skills/manifest.go | 118 ++++++++++++++++ libs/skills/skills.go | 60 ++++++++ libs/skills/testdata/release/RULES.md | 1 + .../release/experimental/beta/SKILL.md | 6 + libs/skills/testdata/release/manifest.json | 8 ++ .../testdata/release/skills/alpha/SKILL.md | 6 + .../release/skills/alpha/references/guide.md | 3 + 14 files changed, 449 insertions(+), 97 deletions(-) create mode 100644 libs/skills/fs.go create mode 100644 libs/skills/fs_test.go create mode 100644 libs/skills/manifest.go create mode 100644 libs/skills/skills.go create mode 100644 libs/skills/testdata/release/RULES.md create mode 100644 libs/skills/testdata/release/experimental/beta/SKILL.md create mode 100644 libs/skills/testdata/release/manifest.json create mode 100644 libs/skills/testdata/release/skills/alpha/SKILL.md create mode 100644 libs/skills/testdata/release/skills/alpha/references/guide.md diff --git a/libs/aitools/installer/errors.go b/libs/aitools/installer/errors.go index 5b7fc8ddf4d..68a6ff3625b 100644 --- a/libs/aitools/installer/errors.go +++ b/libs/aitools/installer/errors.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/databricks/cli/libs/aitools/agents" + "github.com/databricks/cli/libs/skills" ) // ErrNothingInstalled reports that update or uninstall found no install state @@ -85,7 +86,7 @@ var ErrManifestTooLarge = fmt.Errorf("skills manifest is larger than %d MiB", ma // ErrUnsafeManifestPath reports a skills manifest that names a skill or file // outside the skills directory. The command layer classifies it like a // manifest that does not parse. -var ErrUnsafeManifestPath = errors.New("skills manifest names a path outside the skills directory") +var ErrUnsafeManifestPath = skills.ErrUnsafeManifestPath // Stages of fetching skills content, recorded on FetchError so a failed // release lookup can be told apart from a failed download. diff --git a/libs/aitools/installer/installer.go b/libs/aitools/installer/installer.go index 37ffc3259b4..3816d537076 100644 --- a/libs/aitools/installer/installer.go +++ b/libs/aitools/installer/installer.go @@ -26,6 +26,7 @@ import ( "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/log" + "github.com/databricks/cli/libs/skills" "github.com/databricks/cli/libs/versioncheck" "golang.org/x/mod/semver" "golang.org/x/sync/errgroup" @@ -34,8 +35,8 @@ import ( const ( skillsRepoOwner = "databricks" skillsRepoName = "databricks-agent-skills" - stableSkillsRepoPath = "skills" - experimentalRepoPath = "experimental" + stableSkillsRepoPath = skills.StableRepoDir + experimentalRepoPath = skills.ExperimentalRepoDir // fetchConcurrency caps the number of in-flight skill file fetches. // Each file is one HTTPS GET to raw.githubusercontent.com; sequential @@ -194,32 +195,11 @@ func GetSkillsBaseURL(ctx context.Context) string { return "https://raw.githubusercontent.com/" + skillsRepoOwner + "/" + skillsRepoName } -// Manifest describes the skills manifest fetched from the skills repo. -type Manifest struct { - Version string `json:"version"` - UpdatedAt string `json:"updated_at"` - Skills map[string]SkillMeta `json:"skills"` -} - -// SkillMeta describes a single skill entry in the manifest. -type SkillMeta struct { - Version string `json:"version"` - UpdatedAt string `json:"updated_at"` - Files []string `json:"files"` - Description string `json:"description,omitempty"` - MinCLIVer string `json:"min_cli_version,omitempty"` - - // RepoDir is "skills" or "experimental" (manifest field repo_dir). - RepoDir string `json:"repo_dir,omitempty"` - - // SourceName is the upstream skill directory name within RepoDir. - // Set during normalization, not from JSON. - SourceName string `json:"-"` -} - -func (s SkillMeta) IsExperimental() bool { - return s.RepoDir == experimentalRepoPath -} +// Manifest and SkillMeta are defined in libs/skills, which the skill sources share. +type ( + Manifest = skills.Manifest + SkillMeta = skills.SkillMeta +) // InstallOptions controls the behavior of InstallSkillsForAgents. type InstallOptions struct { @@ -281,7 +261,7 @@ func FetchSkillsManifestWithFallback(ctx context.Context, src ManifestSource, re if err != nil { return nil, ref, err } - if err := checkManifestPaths(manifest); err != nil { + if err := skills.CheckManifestPaths(manifest); err != nil { return nil, ref, err } return manifest, ref, nil diff --git a/libs/aitools/installer/installer_test.go b/libs/aitools/installer/installer_test.go index c0345f48181..3690c565c2d 100644 --- a/libs/aitools/installer/installer_test.go +++ b/libs/aitools/installer/installer_test.go @@ -25,6 +25,7 @@ import ( "github.com/databricks/cli/libs/clicompat" "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/log" + "github.com/databricks/cli/libs/skills" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -41,7 +42,7 @@ func (m *mockManifestSource) FetchManifest(_ context.Context, _ string) (*Manife if m.fetchErr != nil { return nil, m.fetchErr } - normalizeManifest(m.manifest) + skills.NormalizeManifest(m.manifest) return m.manifest, nil } diff --git a/libs/aitools/installer/source.go b/libs/aitools/installer/source.go index 0cc06e1fa62..8476ce9485c 100644 --- a/libs/aitools/installer/source.go +++ b/libs/aitools/installer/source.go @@ -5,17 +5,16 @@ import ( "encoding/json" "fmt" "io" - "maps" "net/http" "path" "regexp" - "slices" "strings" "sync" "time" "github.com/databricks/cli/libs/clicompat" "github.com/databricks/cli/libs/log" + "github.com/databricks/cli/libs/skills" ) // ManifestSource abstracts how the skills manifest is fetched. @@ -69,7 +68,7 @@ func (s *GitHubManifestSource) FetchManifest(ctx context.Context, ref string) (* return nil, &FetchError{Stage: FetchStageManifest, StatusCode: resp.StatusCode, Err: fmt.Errorf("failed to parse manifest: %w", err)} } - normalizeManifest(&manifest) + skills.NormalizeManifest(&manifest) return &manifest, nil } @@ -86,49 +85,6 @@ var skillNamePattern = sync.OnceValue(func() *regexp.Regexp { return regexp.MustCompile(`^[a-z0-9]+(-[a-z0-9]+)*$`) }) -// checkManifestPaths fails a manifest that names a skill or file outside its -// directory, or a skill named like the state file. The manifest comes from the -// network, so it must not be able to name ../../.bashrc, and only a broken or -// tampered manifest lists such an entry. The rule is the same on every OS. -// Entries that stay inside their directory but are not portable are left to -// unportableSkill, which skips only that skill. -func checkManifestPaths(m *Manifest) error { - for _, name := range slices.Sorted(maps.Keys(m.Skills)) { - if name == "" || name == "." || name == ".." || name == stateFileName || strings.ContainsAny(name, `/\`) { - return fmt.Errorf("%w: skill name %q", ErrUnsafeManifestPath, name) - } - for _, file := range m.Skills[name].Files { - if escapesDir(file) { - return fmt.Errorf("%w: skill %q lists file %q", ErrUnsafeManifestPath, name, file) - } - } - } - return nil -} - -// escapesDir reports whether file, joined onto a directory, names a path -// outside it on some OS: an absolute path, a Windows drive, or more ".." -// elements than the elements before them, with either slash as the separator. -func escapesDir(file string) bool { - if strings.HasPrefix(file, "/") || strings.HasPrefix(file, `\`) || (len(file) >= 2 && file[1] == ':') { - return true - } - depth := 0 - for _, elem := range strings.FieldsFunc(file, func(r rune) bool { return r == '/' || r == '\\' }) { - switch elem { - case ".": - case "..": - depth-- - if depth < 0 { - return true - } - default: - depth++ - } - } - return false -} - // unportableSkill returns why a skill that stays inside its directory still // cannot be installed the same way on every OS, or "" if it can. Install skips // such a skill and update keeps the installed copy, the way both treat a skill @@ -207,17 +163,3 @@ func isWindowsDeviceName(s string) bool { } return false } - -// normalizeManifest stamps SourceName and defaults RepoDir for older manifests. -func normalizeManifest(m *Manifest) { - if m.Skills == nil { - m.Skills = map[string]SkillMeta{} - } - for name, meta := range m.Skills { - if meta.RepoDir == "" { - meta.RepoDir = stableSkillsRepoPath - } - meta.SourceName = name - m.Skills[name] = meta - } -} diff --git a/libs/aitools/installer/source_test.go b/libs/aitools/installer/source_test.go index dbe96be9a54..eda631cd152 100644 --- a/libs/aitools/installer/source_test.go +++ b/libs/aitools/installer/source_test.go @@ -11,6 +11,7 @@ import ( "github.com/databricks/cli/libs/aitools/agents" "github.com/databricks/cli/libs/cmdio" + "github.com/databricks/cli/libs/skills" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -23,7 +24,7 @@ func TestNormalizeManifestStampsSourceNameAndRepoDir(t *testing.T) { }, } - normalizeManifest(m) + skills.NormalizeManifest(m) stable := m.Skills["databricks-apps"] assert.False(t, stable.IsExperimental()) @@ -41,7 +42,7 @@ func TestManifestHasExperimental(t *testing.T) { stableOnly := &Manifest{Skills: map[string]SkillMeta{ "databricks-apps": {Version: "0.1.0"}, }} - normalizeManifest(stableOnly) + skills.NormalizeManifest(stableOnly) assert.False(t, manifestHasExperimental(stableOnly)) withExperimental := &Manifest{ @@ -50,7 +51,7 @@ func TestManifestHasExperimental(t *testing.T) { "databricks-iceberg": {Version: "0.0.1", RepoDir: experimentalRepoPath}, }, } - normalizeManifest(withExperimental) + skills.NormalizeManifest(withExperimental) assert.True(t, manifestHasExperimental(withExperimental)) } @@ -61,7 +62,7 @@ func TestNormalizeManifestOnlyExperimentalSkills(t *testing.T) { }, } - normalizeManifest(m) + skills.NormalizeManifest(m) got, ok := m.Skills["x"] assert.True(t, ok) @@ -177,7 +178,7 @@ func TestCheckManifestPaths(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { m := &Manifest{Skills: map[string]SkillMeta{tc.skill: {Files: []string{tc.file}}}} - err := checkManifestPaths(m) + err := skills.CheckManifestPaths(m) if tc.wantErr != "" { require.ErrorIs(t, err, ErrUnsafeManifestPath) assert.EqualError(t, err, ErrUnsafeManifestPath.Error()+": "+tc.wantErr) @@ -218,7 +219,7 @@ func TestCheckManifestPathsReportsTheFirstSkillInOrder(t *testing.T) { "../c": {Files: []string{"SKILL.md"}}, }} for range 10 { - assert.EqualError(t, checkManifestPaths(m), ErrUnsafeManifestPath.Error()+`: skill name "../c"`) + assert.EqualError(t, skills.CheckManifestPaths(m), ErrUnsafeManifestPath.Error()+`: skill name "../c"`) } } diff --git a/libs/skills/fs.go b/libs/skills/fs.go new file mode 100644 index 00000000000..e3575915796 --- /dev/null +++ b/libs/skills/fs.go @@ -0,0 +1,97 @@ +package skills + +import ( + "context" + "encoding/json" + "fmt" + "io/fs" + "maps" + "path" + "slices" + "time" +) + +const manifestFile = "manifest.json" + +type fsSource struct { + fsys fs.FS + label string +} + +// NewFSSource returns a Source over fsys, laid out like a skills release: +// manifest.json at the root, and each skill's files under its repo_dir. +func NewFSSource(fsys fs.FS, label string) Source { + return &fsSource{fsys: fsys, label: label} +} + +func (s *fsSource) Catalog(_ context.Context) (*Catalog, error) { + m, err := s.manifest() + if err != nil { + return nil, err + } + catalog := &Catalog{Version: m.Version, Label: s.label, FetchedAt: time.Now()} + if m.CatalogRules != "" { + data, err := fs.ReadFile(s.fsys, m.CatalogRules) + if err != nil { + return nil, fmt.Errorf("read catalog_rules: %w", err) + } + catalog.Rules = string(data) + } + for _, name := range slices.Sorted(maps.Keys(m.Skills)) { + meta := m.Skills[name] + catalog.Skills = append(catalog.Skills, Skill{ + Name: name, + Description: meta.Description, + Version: meta.Version, + Files: meta.Files, + Commands: meta.Commands, + Experimental: meta.IsExperimental(), + }) + } + return catalog, nil +} + +func (s *fsSource) ReadFile(_ context.Context, skill, file string) ([]byte, error) { + m, err := s.manifest() + if err != nil { + return nil, err + } + meta, ok := m.Skills[skill] + if !ok { + return nil, fmt.Errorf("%w: %q", ErrUnknownSkill, skill) + } + if !slices.Contains(meta.Files, file) { + return nil, fmt.Errorf("%w: %q in skill %q", ErrUnknownFile, file, skill) + } + data, err := fs.ReadFile(s.fsys, path.Join(meta.RepoDir, skill, file)) + if err != nil { + return nil, fmt.Errorf("read %q in skill %q: %w", file, skill, err) + } + return data, nil +} + +// manifest reads and checks the release manifest. Every path it names, the +// skill files, repo_dir and catalog_rules, must stay inside the release. +func (s *fsSource) manifest() (*Manifest, error) { + data, err := fs.ReadFile(s.fsys, manifestFile) + if err != nil { + return nil, fmt.Errorf("%w: %w", ErrSourceUnreachable, err) + } + var m Manifest + if err := json.Unmarshal(data, &m); err != nil { + return nil, fmt.Errorf("parse %s: %w", manifestFile, err) + } + NormalizeManifest(&m) + if err := CheckManifestPaths(&m); err != nil { + return nil, err + } + for _, name := range slices.Sorted(maps.Keys(m.Skills)) { + if repoDir := m.Skills[name].RepoDir; EscapesDir(repoDir) { + return nil, fmt.Errorf("%w: skill %q has repo_dir %q", ErrUnsafeManifestPath, name, repoDir) + } + } + if EscapesDir(m.CatalogRules) { + return nil, fmt.Errorf("%w: catalog_rules %q", ErrUnsafeManifestPath, m.CatalogRules) + } + return &m, nil +} diff --git a/libs/skills/fs_test.go b/libs/skills/fs_test.go new file mode 100644 index 00000000000..93426406fa5 --- /dev/null +++ b/libs/skills/fs_test.go @@ -0,0 +1,128 @@ +package skills + +import ( + "os" + "testing" + "testing/fstest" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func fixtureSource() Source { + return NewFSSource(os.DirFS("testdata/release"), "test release") +} + +func mapSource(manifest string) Source { + return NewFSSource(fstest.MapFS{"manifest.json": {Data: []byte(manifest)}}, "map") +} + +func TestCatalogFromFixture(t *testing.T) { + catalog, err := fixtureSource().Catalog(t.Context()) + require.NoError(t, err) + + assert.Equal(t, "1.2.0", catalog.Version) + assert.Equal(t, "test release", catalog.Label) + assert.False(t, catalog.Stale) + assert.False(t, catalog.FetchedAt.IsZero()) + assert.Equal(t, "Use the catalog before you read a skill.\n", catalog.Rules) + + require.Len(t, catalog.Skills, 2) + assert.Equal(t, Skill{ + Name: "alpha", + Description: "A stable skill with a nested file.", + Version: "1.0.0", + Files: []string{"SKILL.md", "references/guide.md"}, + Commands: []string{"jobs", "pipelines"}, + }, catalog.Skills[0]) + assert.Equal(t, Skill{ + Name: "beta", + Description: "An experimental skill.", + Version: "0.1.0", + Files: []string{"SKILL.md"}, + Experimental: true, + }, catalog.Skills[1]) +} + +func TestReadFiles(t *testing.T) { + src := fixtureSource() + + data, err := src.ReadFile(t.Context(), "alpha", "SKILL.md") + require.NoError(t, err) + assert.Contains(t, string(data), "# Alpha") + + data, err = src.ReadFile(t.Context(), "alpha", "references/guide.md") + require.NoError(t, err) + assert.Equal(t, "# Guide\n\nRead this for details.\n", string(data)) + + // An experimental skill is read from its repo_dir. + data, err = src.ReadFile(t.Context(), "beta", "SKILL.md") + require.NoError(t, err) + assert.Contains(t, string(data), "# Beta") +} + +func TestUnknownSkillAndFile(t *testing.T) { + src := fixtureSource() + + _, err := src.ReadFile(t.Context(), "missing", "SKILL.md") + assert.ErrorIs(t, err, ErrUnknownSkill) + + _, err = src.ReadFile(t.Context(), "alpha", "missing.md") + assert.ErrorIs(t, err, ErrUnknownFile) + + // A file of another skill is not a file of this one. + _, err = src.ReadFile(t.Context(), "beta", "references/guide.md") + assert.ErrorIs(t, err, ErrUnknownFile) +} + +func TestUnreachableSource(t *testing.T) { + src := NewFSSource(fstest.MapFS{}, "empty") + + _, err := src.Catalog(t.Context()) + assert.ErrorIs(t, err, ErrSourceUnreachable) + + _, err = src.ReadFile(t.Context(), "alpha", "SKILL.md") + assert.ErrorIs(t, err, ErrSourceUnreachable) +} + +func TestManifestPathsOutsideReleaseAreRejected(t *testing.T) { + for name, manifest := range map[string]string{ + "file outside the skill directory": `{"skills": {"alpha": {"files": ["../../secret"]}}}`, + "repo_dir outside the release": `{"skills": {"alpha": {"files": ["SKILL.md"], "repo_dir": "../other"}}}`, + "catalog_rules outside the release": `{"catalog_rules": "../RULES.md", "skills": {}}`, + } { + t.Run(name, func(t *testing.T) { + src := mapSource(manifest) + + _, err := src.Catalog(t.Context()) + assert.ErrorIs(t, err, ErrUnsafeManifestPath) + }) + } + + // A file the manifest names outside its skill is refused on read too. + _, err := mapSource(`{"skills": {"alpha": {"files": ["../../secret"]}}}`).ReadFile(t.Context(), "alpha", "../../secret") + assert.ErrorIs(t, err, ErrUnsafeManifestPath) +} + +func TestManifestUnknownFieldsAreIgnored(t *testing.T) { + src := mapSource(`{ + "version": "2.0.0", + "future_field": {"anything": true}, + "skills": {"alpha": {"files": ["SKILL.md"], "future_skill_field": 1}} + }`) + + catalog, err := src.Catalog(t.Context()) + require.NoError(t, err) + require.Len(t, catalog.Skills, 1) + assert.Equal(t, []string{"SKILL.md"}, catalog.Skills[0].Files) +} + +func TestManifestWithoutCommandsOrCatalogRules(t *testing.T) { + src := mapSource(`{"version": "1.0.0", "skills": {"alpha": {"files": ["SKILL.md"]}}}`) + + catalog, err := src.Catalog(t.Context()) + require.NoError(t, err) + assert.Empty(t, catalog.Rules) + require.Len(t, catalog.Skills, 1) + assert.Nil(t, catalog.Skills[0].Commands) +} diff --git a/libs/skills/manifest.go b/libs/skills/manifest.go new file mode 100644 index 00000000000..065608f2c14 --- /dev/null +++ b/libs/skills/manifest.go @@ -0,0 +1,118 @@ +package skills + +import ( + "errors" + "fmt" + "maps" + "slices" + "strings" +) + +const ( + // StableRepoDir is the release directory of stable skills (the repo_dir default). + StableRepoDir = "skills" + + // ExperimentalRepoDir is the release directory of experimental skills. + ExperimentalRepoDir = "experimental" + + // StateFileName is the install state file the installer keeps beside the + // skill directories. No skill may take this name. + StateFileName = ".state.json" +) + +// ErrUnsafeManifestPath reports a skills manifest that names a skill or file +// outside the skills directory. The command layer classifies it like a +// manifest that does not parse. +var ErrUnsafeManifestPath = errors.New("skills manifest names a path outside the skills directory") + +// Manifest describes the skills manifest fetched from the skills repo. +type Manifest struct { + Version string `json:"version"` + UpdatedAt string `json:"updated_at"` + Skills map[string]SkillMeta `json:"skills"` + + // CatalogRules names a file at the release root whose text the skills + // catalog shows above the skill list (manifest field catalog_rules). + CatalogRules string `json:"catalog_rules,omitempty"` +} + +// SkillMeta describes a single skill entry in the manifest. +type SkillMeta struct { + Version string `json:"version"` + UpdatedAt string `json:"updated_at"` + Files []string `json:"files"` + Description string `json:"description,omitempty"` + MinCLIVer string `json:"min_cli_version,omitempty"` + + // RepoDir is "skills" or "experimental" (manifest field repo_dir). + RepoDir string `json:"repo_dir,omitempty"` + + // Commands lists the CLI command groups the skill covers (manifest field commands). + Commands []string `json:"commands,omitempty"` + + // SourceName is the upstream skill directory name within RepoDir. + // Set during normalization, not from JSON. + SourceName string `json:"-"` +} + +// IsExperimental reports whether the skill lives in the experimental directory. +func (s SkillMeta) IsExperimental() bool { + return s.RepoDir == ExperimentalRepoDir +} + +// NormalizeManifest stamps SourceName and defaults RepoDir for older manifests. +func NormalizeManifest(m *Manifest) { + if m.Skills == nil { + m.Skills = map[string]SkillMeta{} + } + for name, meta := range m.Skills { + if meta.RepoDir == "" { + meta.RepoDir = StableRepoDir + } + meta.SourceName = name + m.Skills[name] = meta + } +} + +// CheckManifestPaths fails a manifest that names a skill or file outside its +// directory, or a skill named like the state file. The manifest comes from the +// network, so it must not be able to name ../../.bashrc, and only a broken or +// tampered manifest lists such an entry. The rule is the same on every OS. +// Entries that stay inside their directory but are not portable are left to +// the installer, which skips only that skill. +func CheckManifestPaths(m *Manifest) error { + for _, name := range slices.Sorted(maps.Keys(m.Skills)) { + if name == "" || name == "." || name == ".." || name == StateFileName || strings.ContainsAny(name, `/\`) { + return fmt.Errorf("%w: skill name %q", ErrUnsafeManifestPath, name) + } + for _, file := range m.Skills[name].Files { + if EscapesDir(file) { + return fmt.Errorf("%w: skill %q lists file %q", ErrUnsafeManifestPath, name, file) + } + } + } + return nil +} + +// EscapesDir reports whether file, joined onto a directory, names a path +// outside it on some OS: an absolute path, a Windows drive, or more ".." +// elements than the elements before them, with either slash as the separator. +func EscapesDir(file string) bool { + if strings.HasPrefix(file, "/") || strings.HasPrefix(file, `\`) || (len(file) >= 2 && file[1] == ':') { + return true + } + depth := 0 + for _, elem := range strings.FieldsFunc(file, func(r rune) bool { return r == '/' || r == '\\' }) { + switch elem { + case ".": + case "..": + depth-- + if depth < 0 { + return true + } + default: + depth++ + } + } + return false +} diff --git a/libs/skills/skills.go b/libs/skills/skills.go new file mode 100644 index 00000000000..1d87379c621 --- /dev/null +++ b/libs/skills/skills.go @@ -0,0 +1,60 @@ +// Package skills lists and reads Databricks skills from any source that serves +// a skills release: a published release, a bundled snapshot or a local folder. +package skills + +import ( + "context" + "errors" + "time" +) + +var ( + // ErrUnknownSkill reports a skill name the catalog does not list. + ErrUnknownSkill = errors.New("unknown skill") + + // ErrUnknownFile reports a file the catalog does not list for the skill. + ErrUnknownFile = errors.New("unknown skill file") + + // ErrSourceUnreachable reports a source whose release cannot be read. + ErrSourceUnreachable = errors.New("skills source unreachable") +) + +// Skill is one skill in a catalog. +type Skill struct { + Name string + Description string + Version string + + // Files lists the skill's files relative to the skill directory, SKILL.md included. + Files []string + + // Commands lists the CLI command groups the skill covers. + Commands []string + + Experimental bool +} + +// Catalog is the set of skills a source serves. +type Catalog struct { + // Skills are sorted by name. + Skills []Skill + + // Version is the release version. + Version string + + // Label says where the catalog came from. + Label string + + FetchedAt time.Time + Stale bool + + // Rules is text shown above the catalog, empty when the release has none. + Rules string +} + +// Source serves skills. Callers list skills and their files from the catalog, +// and read file contents with ReadFile. +type Source interface { + Catalog(ctx context.Context) (*Catalog, error) + ReadFile(ctx context.Context, skill, path string) ([]byte, error) +} diff --git a/libs/skills/testdata/release/RULES.md b/libs/skills/testdata/release/RULES.md new file mode 100644 index 00000000000..1015835d576 --- /dev/null +++ b/libs/skills/testdata/release/RULES.md @@ -0,0 +1 @@ +Use the catalog before you read a skill. diff --git a/libs/skills/testdata/release/experimental/beta/SKILL.md b/libs/skills/testdata/release/experimental/beta/SKILL.md new file mode 100644 index 00000000000..30a944da32e --- /dev/null +++ b/libs/skills/testdata/release/experimental/beta/SKILL.md @@ -0,0 +1,6 @@ +--- +name: beta +description: An experimental skill. +--- + +# Beta diff --git a/libs/skills/testdata/release/manifest.json b/libs/skills/testdata/release/manifest.json new file mode 100644 index 00000000000..b4ae3908658 --- /dev/null +++ b/libs/skills/testdata/release/manifest.json @@ -0,0 +1,8 @@ +{ + "version": "1.2.0", + "catalog_rules": "RULES.md", + "skills": { + "beta": {"version": "0.1.0", "description": "An experimental skill.", "files": ["SKILL.md"], "repo_dir": "experimental"}, + "alpha": {"version": "1.0.0", "description": "A stable skill with a nested file.", "files": ["SKILL.md", "references/guide.md"], "commands": ["jobs", "pipelines"], "repo_dir": "skills"} + } +} diff --git a/libs/skills/testdata/release/skills/alpha/SKILL.md b/libs/skills/testdata/release/skills/alpha/SKILL.md new file mode 100644 index 00000000000..aeaecf6bcea --- /dev/null +++ b/libs/skills/testdata/release/skills/alpha/SKILL.md @@ -0,0 +1,6 @@ +--- +name: alpha +description: A stable skill with a nested file. +--- + +# Alpha diff --git a/libs/skills/testdata/release/skills/alpha/references/guide.md b/libs/skills/testdata/release/skills/alpha/references/guide.md new file mode 100644 index 00000000000..0ab921f5810 --- /dev/null +++ b/libs/skills/testdata/release/skills/alpha/references/guide.md @@ -0,0 +1,3 @@ +# Guide + +Read this for details. From 79c67cda4f5c6f33e587419887650572585ab95e Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Wed, 25 Nov 2026 18:56:48 +0000 Subject: [PATCH 08/25] Share the install state file name with libs/skills The installer and libs/skills both reserve .state.json. Define the name once in libs/skills and have the installer use it. Co-authored-by: Isaac --- libs/aitools/installer/state.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/libs/aitools/installer/state.go b/libs/aitools/installer/state.go index 599cacab00b..0e0310e48f1 100644 --- a/libs/aitools/installer/state.go +++ b/libs/aitools/installer/state.go @@ -13,6 +13,7 @@ import ( "github.com/databricks/cli/libs/atomicfile" "github.com/databricks/cli/libs/env" + "github.com/databricks/cli/libs/skills" ) // clearFileRecords removes all file-provenance entries belonging to a skill @@ -27,7 +28,8 @@ func clearFileRecords(files map[string]FileRecord, skillName string) { } } -const stateFileName = ".state.json" +// stateFileName is the install state file; libs/skills reserves the same name. +const stateFileName = skills.StateFileName // CurrentSchemaVersion is the on-disk state schema version this CLI writes. v2 // added the Plugins and Files maps; v3 adds the optional MCP section. Older state From 4530158a600203b57f46002517a96aa1300002c1 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Wed, 25 Nov 2026 19:13:24 +0000 Subject: [PATCH 09/25] Compare skill fixtures with normalized line endings The Windows CI checkout turns the LF fixtures into CRLF, so the exact content assertions failed. Normalize line endings before comparing. Co-authored-by: Isaac --- libs/skills/fs_test.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/libs/skills/fs_test.go b/libs/skills/fs_test.go index 93426406fa5..c681f78acd9 100644 --- a/libs/skills/fs_test.go +++ b/libs/skills/fs_test.go @@ -2,6 +2,7 @@ package skills import ( "os" + "strings" "testing" "testing/fstest" @@ -13,6 +14,12 @@ func fixtureSource() Source { return NewFSSource(os.DirFS("testdata/release"), "test release") } +// lf normalizes line endings, so the fixtures compare equal on a checkout +// that turns LF into CRLF, as Windows does. +func lf(s string) string { + return strings.ReplaceAll(s, "\r\n", "\n") +} + func mapSource(manifest string) Source { return NewFSSource(fstest.MapFS{"manifest.json": {Data: []byte(manifest)}}, "map") } @@ -25,7 +32,7 @@ func TestCatalogFromFixture(t *testing.T) { assert.Equal(t, "test release", catalog.Label) assert.False(t, catalog.Stale) assert.False(t, catalog.FetchedAt.IsZero()) - assert.Equal(t, "Use the catalog before you read a skill.\n", catalog.Rules) + assert.Equal(t, "Use the catalog before you read a skill.\n", lf(catalog.Rules)) require.Len(t, catalog.Skills, 2) assert.Equal(t, Skill{ @@ -53,7 +60,7 @@ func TestReadFiles(t *testing.T) { data, err = src.ReadFile(t.Context(), "alpha", "references/guide.md") require.NoError(t, err) - assert.Equal(t, "# Guide\n\nRead this for details.\n", string(data)) + assert.Equal(t, "# Guide\n\nRead this for details.\n", lf(string(data))) // An experimental skill is read from its repo_dir. data, err = src.ReadFile(t.Context(), "beta", "SKILL.md") From b61b62d13ba2e5064c27cf1366563c28b8daee07 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Wed, 25 Nov 2026 19:55:11 +0000 Subject: [PATCH 10/25] Address review on the skills source Clean catalog_rules before reading it, expose min_cli_version on Skill, document the Catalog fields and the release-relative paths the manifest may name. Co-authored-by: Isaac --- libs/skills/fs.go | 18 ++++++++++++------ libs/skills/fs_test.go | 20 ++++++++++++++++++++ libs/skills/manifest.go | 9 +++++---- libs/skills/skills.go | 16 ++++++++++++++-- 4 files changed, 51 insertions(+), 12 deletions(-) diff --git a/libs/skills/fs.go b/libs/skills/fs.go index e3575915796..2718d9fc65b 100644 --- a/libs/skills/fs.go +++ b/libs/skills/fs.go @@ -40,12 +40,13 @@ func (s *fsSource) Catalog(_ context.Context) (*Catalog, error) { for _, name := range slices.Sorted(maps.Keys(m.Skills)) { meta := m.Skills[name] catalog.Skills = append(catalog.Skills, Skill{ - Name: name, - Description: meta.Description, - Version: meta.Version, - Files: meta.Files, - Commands: meta.Commands, - Experimental: meta.IsExperimental(), + Name: name, + Description: meta.Description, + Version: meta.Version, + Files: meta.Files, + Commands: meta.Commands, + MinCLIVersion: meta.MinCLIVer, + Experimental: meta.IsExperimental(), }) } return catalog, nil @@ -90,6 +91,11 @@ func (s *fsSource) manifest() (*Manifest, error) { return nil, fmt.Errorf("%w: skill %q has repo_dir %q", ErrUnsafeManifestPath, name, repoDir) } } + if m.CatalogRules != "" { + // Clean the path the way skill files are cleaned by path.Join, so that + // "./RULES.md" and "docs/../RULES.md" are read like "RULES.md". + m.CatalogRules = path.Clean(m.CatalogRules) + } if EscapesDir(m.CatalogRules) { return nil, fmt.Errorf("%w: catalog_rules %q", ErrUnsafeManifestPath, m.CatalogRules) } diff --git a/libs/skills/fs_test.go b/libs/skills/fs_test.go index c681f78acd9..e78cdef55c7 100644 --- a/libs/skills/fs_test.go +++ b/libs/skills/fs_test.go @@ -133,3 +133,23 @@ func TestManifestWithoutCommandsOrCatalogRules(t *testing.T) { require.Len(t, catalog.Skills, 1) assert.Nil(t, catalog.Skills[0].Commands) } + +func TestCatalogRulesPathIsCleaned(t *testing.T) { + for _, rules := range []string{"./RULES.md", "docs/../RULES.md"} { + src := NewFSSource(fstest.MapFS{ + "manifest.json": {Data: []byte(`{"catalog_rules": "` + rules + `", "skills": {}}`)}, + "RULES.md": {Data: []byte("rules")}, + }, "map") + + catalog, err := src.Catalog(t.Context()) + require.NoError(t, err, rules) + assert.Equal(t, "rules", catalog.Rules, rules) + } +} + +func TestManifestMinCLIVersionIsListed(t *testing.T) { + catalog, err := mapSource(`{"skills": {"alpha": {"files": ["SKILL.md"], "min_cli_version": "99.0.0"}}}`).Catalog(t.Context()) + require.NoError(t, err) + require.Len(t, catalog.Skills, 1) + assert.Equal(t, "99.0.0", catalog.Skills[0].MinCLIVersion) +} diff --git a/libs/skills/manifest.go b/libs/skills/manifest.go index 065608f2c14..a8b4c5a2d13 100644 --- a/libs/skills/manifest.go +++ b/libs/skills/manifest.go @@ -20,8 +20,9 @@ const ( StateFileName = ".state.json" ) -// ErrUnsafeManifestPath reports a skills manifest that names a skill or file -// outside the skills directory. The command layer classifies it like a +// ErrUnsafeManifestPath reports a skills manifest that names a skill directory, +// a skill file or catalog_rules outside the release. Its message keeps the +// wording install has always printed. The command layer classifies it like a // manifest that does not parse. var ErrUnsafeManifestPath = errors.New("skills manifest names a path outside the skills directory") @@ -31,8 +32,8 @@ type Manifest struct { UpdatedAt string `json:"updated_at"` Skills map[string]SkillMeta `json:"skills"` - // CatalogRules names a file at the release root whose text the skills - // catalog shows above the skill list (manifest field catalog_rules). + // CatalogRules names a file in the release, relative to its root, whose text + // the skills catalog shows above the skill list (manifest field catalog_rules). CatalogRules string `json:"catalog_rules,omitempty"` } diff --git a/libs/skills/skills.go b/libs/skills/skills.go index 1d87379c621..1247a40e944 100644 --- a/libs/skills/skills.go +++ b/libs/skills/skills.go @@ -31,12 +31,19 @@ type Skill struct { // Commands lists the CLI command groups the skill covers. Commands []string + // MinCLIVersion is the oldest CLI version that can use the skill (manifest + // field min_cli_version). Install skips the skill on an older CLI, so callers + // that install skills must apply the same check. + MinCLIVersion string + Experimental bool } // Catalog is the set of skills a source serves. type Catalog struct { - // Skills are sorted by name. + // Skills are sorted by name. The catalog lists every skill the release + // names. Install also skips a skill with a non-portable name or file path, + // and a skill whose MinCLIVersion is newer than the running CLI. Skills []Skill // Version is the release version. @@ -45,8 +52,13 @@ type Catalog struct { // Label says where the catalog came from. Label string + // FetchedAt is when the source produced the catalog. A source that serves + // a cached copy sets it to the time the copy was fetched. FetchedAt time.Time - Stale bool + + // Stale reports that the source served a cached copy it could not refresh. + // Sources that always read the release themselves leave it false. + Stale bool // Rules is text shown above the catalog, empty when the release has none. Rules string From 2906664054dead439737d5f0e3071ea93a4e3b92 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Thu, 26 Nov 2026 14:47:32 +0000 Subject: [PATCH 11/25] Skill source: unexport escapesDir, reject a catalog_rules directory Keep the path helper unexported since only libs/skills calls it, reject a catalog_rules path that cleans to a directory, and test a missing rules file. Drop the min_cli_version field, which is not in the skill interface the package needs yet. Co-authored-by: Isaac --- libs/skills/fs.go | 18 +++++++++--------- libs/skills/fs_test.go | 9 ++++----- libs/skills/manifest.go | 6 +++--- libs/skills/skills.go | 9 +-------- 4 files changed, 17 insertions(+), 25 deletions(-) diff --git a/libs/skills/fs.go b/libs/skills/fs.go index 2718d9fc65b..3bfd7cd389a 100644 --- a/libs/skills/fs.go +++ b/libs/skills/fs.go @@ -40,13 +40,12 @@ func (s *fsSource) Catalog(_ context.Context) (*Catalog, error) { for _, name := range slices.Sorted(maps.Keys(m.Skills)) { meta := m.Skills[name] catalog.Skills = append(catalog.Skills, Skill{ - Name: name, - Description: meta.Description, - Version: meta.Version, - Files: meta.Files, - Commands: meta.Commands, - MinCLIVersion: meta.MinCLIVer, - Experimental: meta.IsExperimental(), + Name: name, + Description: meta.Description, + Version: meta.Version, + Files: meta.Files, + Commands: meta.Commands, + Experimental: meta.IsExperimental(), }) } return catalog, nil @@ -87,7 +86,7 @@ func (s *fsSource) manifest() (*Manifest, error) { return nil, err } for _, name := range slices.Sorted(maps.Keys(m.Skills)) { - if repoDir := m.Skills[name].RepoDir; EscapesDir(repoDir) { + if repoDir := m.Skills[name].RepoDir; escapesDir(repoDir) { return nil, fmt.Errorf("%w: skill %q has repo_dir %q", ErrUnsafeManifestPath, name, repoDir) } } @@ -96,7 +95,8 @@ func (s *fsSource) manifest() (*Manifest, error) { // "./RULES.md" and "docs/../RULES.md" are read like "RULES.md". m.CatalogRules = path.Clean(m.CatalogRules) } - if EscapesDir(m.CatalogRules) { + // "docs/.." cleans to ".", a directory that cannot be read as rules. + if m.CatalogRules == "." || escapesDir(m.CatalogRules) { return nil, fmt.Errorf("%w: catalog_rules %q", ErrUnsafeManifestPath, m.CatalogRules) } return &m, nil diff --git a/libs/skills/fs_test.go b/libs/skills/fs_test.go index e78cdef55c7..ac069a3f93b 100644 --- a/libs/skills/fs_test.go +++ b/libs/skills/fs_test.go @@ -97,6 +97,7 @@ func TestManifestPathsOutsideReleaseAreRejected(t *testing.T) { "file outside the skill directory": `{"skills": {"alpha": {"files": ["../../secret"]}}}`, "repo_dir outside the release": `{"skills": {"alpha": {"files": ["SKILL.md"], "repo_dir": "../other"}}}`, "catalog_rules outside the release": `{"catalog_rules": "../RULES.md", "skills": {}}`, + "catalog_rules naming a directory": `{"catalog_rules": "docs/..", "skills": {}}`, } { t.Run(name, func(t *testing.T) { src := mapSource(manifest) @@ -147,9 +148,7 @@ func TestCatalogRulesPathIsCleaned(t *testing.T) { } } -func TestManifestMinCLIVersionIsListed(t *testing.T) { - catalog, err := mapSource(`{"skills": {"alpha": {"files": ["SKILL.md"], "min_cli_version": "99.0.0"}}}`).Catalog(t.Context()) - require.NoError(t, err) - require.Len(t, catalog.Skills, 1) - assert.Equal(t, "99.0.0", catalog.Skills[0].MinCLIVersion) +func TestMissingCatalogRulesIsReported(t *testing.T) { + _, err := mapSource(`{"catalog_rules": "RULES.md", "skills": {}}`).Catalog(t.Context()) + assert.ErrorIs(t, err, os.ErrNotExist) } diff --git a/libs/skills/manifest.go b/libs/skills/manifest.go index a8b4c5a2d13..11c4a9b8bc1 100644 --- a/libs/skills/manifest.go +++ b/libs/skills/manifest.go @@ -87,7 +87,7 @@ func CheckManifestPaths(m *Manifest) error { return fmt.Errorf("%w: skill name %q", ErrUnsafeManifestPath, name) } for _, file := range m.Skills[name].Files { - if EscapesDir(file) { + if escapesDir(file) { return fmt.Errorf("%w: skill %q lists file %q", ErrUnsafeManifestPath, name, file) } } @@ -95,10 +95,10 @@ func CheckManifestPaths(m *Manifest) error { return nil } -// EscapesDir reports whether file, joined onto a directory, names a path +// escapesDir reports whether file, joined onto a directory, names a path // outside it on some OS: an absolute path, a Windows drive, or more ".." // elements than the elements before them, with either slash as the separator. -func EscapesDir(file string) bool { +func escapesDir(file string) bool { if strings.HasPrefix(file, "/") || strings.HasPrefix(file, `\`) || (len(file) >= 2 && file[1] == ':') { return true } diff --git a/libs/skills/skills.go b/libs/skills/skills.go index 1247a40e944..2ff80d81b14 100644 --- a/libs/skills/skills.go +++ b/libs/skills/skills.go @@ -31,19 +31,12 @@ type Skill struct { // Commands lists the CLI command groups the skill covers. Commands []string - // MinCLIVersion is the oldest CLI version that can use the skill (manifest - // field min_cli_version). Install skips the skill on an older CLI, so callers - // that install skills must apply the same check. - MinCLIVersion string - Experimental bool } // Catalog is the set of skills a source serves. type Catalog struct { - // Skills are sorted by name. The catalog lists every skill the release - // names. Install also skips a skill with a non-portable name or file path, - // and a skill whose MinCLIVersion is newer than the running CLI. + // Skills are sorted by name, one per skill the release names. Skills []Skill // Version is the release version. From ddbdb00afedf958ef344cef8a02d6290cffe322a Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Thu, 26 Nov 2026 15:15:46 +0000 Subject: [PATCH 12/25] Carry the minimum CLI version on skills catalog entries Skill now has MinCLIVer, read from the manifest's min_cli_version, so a caller can apply the same rule install uses. The fixture covers it. Co-authored-by: Isaac --- libs/skills/fs.go | 1 + libs/skills/fs_test.go | 1 + libs/skills/skills.go | 4 +++- libs/skills/testdata/release/manifest.json | 2 +- 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/libs/skills/fs.go b/libs/skills/fs.go index 3bfd7cd389a..69b37d4f59a 100644 --- a/libs/skills/fs.go +++ b/libs/skills/fs.go @@ -43,6 +43,7 @@ func (s *fsSource) Catalog(_ context.Context) (*Catalog, error) { Name: name, Description: meta.Description, Version: meta.Version, + MinCLIVer: meta.MinCLIVer, Files: meta.Files, Commands: meta.Commands, Experimental: meta.IsExperimental(), diff --git a/libs/skills/fs_test.go b/libs/skills/fs_test.go index ac069a3f93b..951e5ad19f2 100644 --- a/libs/skills/fs_test.go +++ b/libs/skills/fs_test.go @@ -39,6 +39,7 @@ func TestCatalogFromFixture(t *testing.T) { Name: "alpha", Description: "A stable skill with a nested file.", Version: "1.0.0", + MinCLIVer: "0.300.0", Files: []string{"SKILL.md", "references/guide.md"}, Commands: []string{"jobs", "pipelines"}, }, catalog.Skills[0]) diff --git a/libs/skills/skills.go b/libs/skills/skills.go index 2ff80d81b14..38d4a86d422 100644 --- a/libs/skills/skills.go +++ b/libs/skills/skills.go @@ -24,6 +24,7 @@ type Skill struct { Name string Description string Version string + MinCLIVer string // Files lists the skill's files relative to the skill directory, SKILL.md included. Files []string @@ -36,7 +37,8 @@ type Skill struct { // Catalog is the set of skills a source serves. type Catalog struct { - // Skills are sorted by name, one per skill the release names. + // Skills are sorted by name. Install also skips non-portable names and + // paths, which the catalog does not check yet. Skills []Skill // Version is the release version. diff --git a/libs/skills/testdata/release/manifest.json b/libs/skills/testdata/release/manifest.json index b4ae3908658..01d1e41a23a 100644 --- a/libs/skills/testdata/release/manifest.json +++ b/libs/skills/testdata/release/manifest.json @@ -3,6 +3,6 @@ "catalog_rules": "RULES.md", "skills": { "beta": {"version": "0.1.0", "description": "An experimental skill.", "files": ["SKILL.md"], "repo_dir": "experimental"}, - "alpha": {"version": "1.0.0", "description": "A stable skill with a nested file.", "files": ["SKILL.md", "references/guide.md"], "commands": ["jobs", "pipelines"], "repo_dir": "skills"} + "alpha": {"version": "1.0.0", "description": "A stable skill with a nested file.", "files": ["SKILL.md", "references/guide.md"], "min_cli_version": "0.300.0", "commands": ["jobs", "pipelines"], "repo_dir": "skills"} } } From 41dfd3d2b679ac23591c5e4f02e324482eae8bb9 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Thu, 26 Nov 2026 09:00:22 +0000 Subject: [PATCH 13/25] Add the skills command group behind DATABRICKS_SKILLS_PREVIEW Register the hidden skills command group only when DATABRICKS_SKILLS_PREVIEW is set. Its five subcommands are stubs that report they are not implemented yet. Add guards for the feature and for its hints switch, DATABRICKS_SKILLS_HINTS, and a resolver for the folder in DATABRICKS_SKILLS_DIR, with an acceptance fixture release that later changes reuse. With the variable unset, the command group is not registered and nothing else changes. Co-authored-by: Isaac --- acceptance/cmd/skills/disabled/out.test.toml | 1 + acceptance/cmd/skills/disabled/output.txt | 5 ++ acceptance/cmd/skills/disabled/script | 3 + acceptance/cmd/skills/disabled/test.toml | 1 + acceptance/cmd/skills/enabled/out.test.toml | 1 + acceptance/cmd/skills/enabled/output.txt | 41 ++++++++++++ acceptance/cmd/skills/enabled/script | 10 +++ acceptance/cmd/skills/enabled/test.toml | 2 + acceptance/cmd/skills/release/manifest.json | 6 ++ .../skills/release/skills/demo-skill/SKILL.md | 6 ++ cmd/cmd.go | 5 ++ cmd/skills/list.go | 14 ++++ cmd/skills/list_files.go | 14 ++++ cmd/skills/read.go | 14 ++++ cmd/skills/read_file.go | 14 ++++ cmd/skills/search.go | 14 ++++ cmd/skills/skills.go | 33 ++++++++++ libs/skills/guard.go | 34 ++++++++++ libs/skills/guard_test.go | 64 +++++++++++++++++++ libs/skills/resolve.go | 40 ++++++++++++ libs/skills/resolve_test.go | 43 +++++++++++++ 21 files changed, 365 insertions(+) create mode 100644 acceptance/cmd/skills/disabled/out.test.toml create mode 100644 acceptance/cmd/skills/disabled/output.txt create mode 100644 acceptance/cmd/skills/disabled/script create mode 100644 acceptance/cmd/skills/disabled/test.toml create mode 100644 acceptance/cmd/skills/enabled/out.test.toml create mode 100644 acceptance/cmd/skills/enabled/output.txt create mode 100644 acceptance/cmd/skills/enabled/script create mode 100644 acceptance/cmd/skills/enabled/test.toml create mode 100644 acceptance/cmd/skills/release/manifest.json create mode 100644 acceptance/cmd/skills/release/skills/demo-skill/SKILL.md create mode 100644 cmd/skills/list.go create mode 100644 cmd/skills/list_files.go create mode 100644 cmd/skills/read.go create mode 100644 cmd/skills/read_file.go create mode 100644 cmd/skills/search.go create mode 100644 cmd/skills/skills.go create mode 100644 libs/skills/guard.go create mode 100644 libs/skills/guard_test.go create mode 100644 libs/skills/resolve.go create mode 100644 libs/skills/resolve_test.go diff --git a/acceptance/cmd/skills/disabled/out.test.toml b/acceptance/cmd/skills/disabled/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/skills/disabled/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/skills/disabled/output.txt b/acceptance/cmd/skills/disabled/output.txt new file mode 100644 index 00000000000..0c7e76db4aa --- /dev/null +++ b/acceptance/cmd/skills/disabled/output.txt @@ -0,0 +1,5 @@ + +>>> env -u DATABRICKS_SKILLS_PREVIEW [CLI] skills list +Error: unknown command "skills" for "databricks" + +>>> env -u DATABRICKS_SKILLS_PREVIEW [CLI] --help diff --git a/acceptance/cmd/skills/disabled/script b/acceptance/cmd/skills/disabled/script new file mode 100644 index 00000000000..f06f9b1b9fd --- /dev/null +++ b/acceptance/cmd/skills/disabled/script @@ -0,0 +1,3 @@ +# Unset, the skills group is not registered: it is an unknown command and is not listed in help. +musterr trace env -u DATABRICKS_SKILLS_PREVIEW $CLI skills list +trace env -u DATABRICKS_SKILLS_PREVIEW $CLI --help | contains.py "! skills " > /dev/null diff --git a/acceptance/cmd/skills/disabled/test.toml b/acceptance/cmd/skills/disabled/test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/skills/disabled/test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/skills/enabled/out.test.toml b/acceptance/cmd/skills/enabled/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/skills/enabled/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/skills/enabled/output.txt b/acceptance/cmd/skills/enabled/output.txt new file mode 100644 index 00000000000..f376535e2de --- /dev/null +++ b/acceptance/cmd/skills/enabled/output.txt @@ -0,0 +1,41 @@ + +>>> [CLI] skills --help +List, read and search Databricks skills + +Usage: + databricks skills [command] + +Available Commands: + list List the available skills + list-files List the files of a skill + read Read a skill's instructions + read-file Read one file of a skill + search Search the skills for words + +Flags: + -h, --help[=true|false] help for skills + +Global Flags: + --debug[=true|false] enable debug logging + -o, --output type output type: text or json (default text) + -p, --profile string ~/.databrickscfg profile + -t, --target string bundle target to use (if applicable) + +Use "databricks skills [command] --help" for more information about a command. + +>>> [CLI] --help + +>>> [CLI] skills list +Error: databricks skills list is not implemented yet + +>>> [CLI] skills read demo-skill +Error: databricks skills read is not implemented yet + +>>> [CLI] skills list-files demo-skill +Error: databricks skills list-files is not implemented yet + +>>> [CLI] skills read-file demo-skill SKILL.md +Error: databricks skills read-file is not implemented yet + +>>> [CLI] skills search skill words +Error: databricks skills search is not implemented yet diff --git a/acceptance/cmd/skills/enabled/script b/acceptance/cmd/skills/enabled/script new file mode 100644 index 00000000000..ebd3804ae95 --- /dev/null +++ b/acceptance/cmd/skills/enabled/script @@ -0,0 +1,10 @@ +# With the variable set, the group lists its five subcommands and stays hidden from the root help. +trace $CLI skills --help +trace $CLI --help | contains.py "! skills " > /dev/null + +# Each subcommand is a stub that exits non-zero with the not-implemented message. +musterr trace $CLI skills list +musterr trace $CLI skills read demo-skill +musterr trace $CLI skills list-files demo-skill +musterr trace $CLI skills read-file demo-skill SKILL.md +musterr trace $CLI skills search skill words diff --git a/acceptance/cmd/skills/enabled/test.toml b/acceptance/cmd/skills/enabled/test.toml new file mode 100644 index 00000000000..27401a415e2 --- /dev/null +++ b/acceptance/cmd/skills/enabled/test.toml @@ -0,0 +1,2 @@ +Cloud = false +Env.DATABRICKS_SKILLS_PREVIEW = "1" diff --git a/acceptance/cmd/skills/release/manifest.json b/acceptance/cmd/skills/release/manifest.json new file mode 100644 index 00000000000..fe67500f60a --- /dev/null +++ b/acceptance/cmd/skills/release/manifest.json @@ -0,0 +1,6 @@ +{ + "version": "0.0.1", + "skills": { + "demo-skill": {"version": "0.0.1", "description": "A skill for tests.", "files": ["SKILL.md"]} + } +} diff --git a/acceptance/cmd/skills/release/skills/demo-skill/SKILL.md b/acceptance/cmd/skills/release/skills/demo-skill/SKILL.md new file mode 100644 index 00000000000..47cd5d23ccd --- /dev/null +++ b/acceptance/cmd/skills/release/skills/demo-skill/SKILL.md @@ -0,0 +1,6 @@ +--- +name: demo-skill +description: A skill for tests. +--- + +# Demo skill diff --git a/cmd/cmd.go b/cmd/cmd.go index 2a987c114b4..4f24d2474ad 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -26,10 +26,12 @@ import ( "github.com/databricks/cli/cmd/root" "github.com/databricks/cli/cmd/sandbox" "github.com/databricks/cli/cmd/selftest" + skillscmd "github.com/databricks/cli/cmd/skills" "github.com/databricks/cli/cmd/sync" "github.com/databricks/cli/cmd/version" "github.com/databricks/cli/cmd/workspace" "github.com/databricks/cli/libs/cmdgroup" + "github.com/databricks/cli/libs/skills" "github.com/spf13/cobra" ) @@ -82,6 +84,9 @@ func workspaceSpec(spec root.CommandSpec) root.CommandSpec { func New(ctx context.Context) *root.Tree { cli := root.NewTree(ctx) cli.Add(topLevelSpecs()...) + if skills.Enabled(ctx) { + cli.Add(skillscmd.Spec) + } // Add workspace command groups, filtering out empty groups or groups with only hidden commands. cli.AddGroups(append(workspace.Groups(), cobra.Group{ diff --git a/cmd/skills/list.go b/cmd/skills/list.go new file mode 100644 index 00000000000..8d4d116d87a --- /dev/null +++ b/cmd/skills/list.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newListCmd() *cobra.Command { + return &cobra.Command{ + Use: "list", + Short: "List the available skills", + Args: cobra.NoArgs, + RunE: notImplemented, + } +} diff --git a/cmd/skills/list_files.go b/cmd/skills/list_files.go new file mode 100644 index 00000000000..016d2cecfe0 --- /dev/null +++ b/cmd/skills/list_files.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newListFilesCmd() *cobra.Command { + return &cobra.Command{ + Use: "list-files ", + Short: "List the files of a skill", + Args: cobra.ExactArgs(1), + RunE: notImplemented, + } +} diff --git a/cmd/skills/read.go b/cmd/skills/read.go new file mode 100644 index 00000000000..2bf7814e55f --- /dev/null +++ b/cmd/skills/read.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newReadCmd() *cobra.Command { + return &cobra.Command{ + Use: "read ", + Short: "Read a skill's instructions", + Args: cobra.ExactArgs(1), + RunE: notImplemented, + } +} diff --git a/cmd/skills/read_file.go b/cmd/skills/read_file.go new file mode 100644 index 00000000000..e6172eb0d2b --- /dev/null +++ b/cmd/skills/read_file.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newReadFileCmd() *cobra.Command { + return &cobra.Command{ + Use: "read-file ", + Short: "Read one file of a skill", + Args: cobra.ExactArgs(2), + RunE: notImplemented, + } +} diff --git a/cmd/skills/search.go b/cmd/skills/search.go new file mode 100644 index 00000000000..e46451e2bdb --- /dev/null +++ b/cmd/skills/search.go @@ -0,0 +1,14 @@ +package skills + +import ( + "github.com/spf13/cobra" +) + +func newSearchCmd() *cobra.Command { + return &cobra.Command{ + Use: "search ", + Short: "Search the skills for words", + Args: cobra.MinimumNArgs(1), + RunE: notImplemented, + } +} diff --git a/cmd/skills/skills.go b/cmd/skills/skills.go new file mode 100644 index 00000000000..963add4ee16 --- /dev/null +++ b/cmd/skills/skills.go @@ -0,0 +1,33 @@ +// Package skills implements the `databricks skills` command group. The group +// is registered only when libs/skills.Enabled is true, and is hidden from help. +package skills + +import ( + "context" + "fmt" + + "github.com/databricks/cli/cmd/root" + "github.com/spf13/cobra" +) + +// Spec declares the skills command group. +var Spec = root.CommandSpec{ + Use: "skills", + Short: "List, read and search Databricks skills", + Hidden: true, + Build: buildCommand, +} + +func buildCommand(_ context.Context, cmd *cobra.Command) { + cmd.AddCommand(newListCmd()) + cmd.AddCommand(newReadCmd()) + cmd.AddCommand(newListFilesCmd()) + cmd.AddCommand(newReadFileCmd()) + cmd.AddCommand(newSearchCmd()) +} + +// notImplemented is the run function of every subcommand until its own change +// lands. +func notImplemented(cmd *cobra.Command, _ []string) error { + return fmt.Errorf("%s is not implemented yet", cmd.CommandPath()) +} diff --git a/libs/skills/guard.go b/libs/skills/guard.go new file mode 100644 index 00000000000..dc3182dfabf --- /dev/null +++ b/libs/skills/guard.go @@ -0,0 +1,34 @@ +package skills + +import ( + "context" + + "github.com/databricks/cli/libs/env" +) + +const ( + // previewEnv turns the skills feature on. Off, the skills command group is + // not registered and nothing else in the feature runs. + previewEnv = "DATABRICKS_SKILLS_PREVIEW" + + // hintsEnv turns on skill hints. It only has an effect while previewEnv is set. + hintsEnv = "DATABRICKS_SKILLS_HINTS" +) + +// Enabled reports whether the skills feature is on. It is the gate for the +// whole feature: unless DATABRICKS_SKILLS_PREVIEW is set to a true value, the +// skills command group is not registered. +func Enabled(ctx context.Context) bool { + return envTrue(ctx, previewEnv) +} + +// HintsEnabled reports whether skill hints are on. Hints need the feature on +// and DATABRICKS_SKILLS_HINTS set to a true value of their own. +func HintsEnabled(ctx context.Context) bool { + return Enabled(ctx) && envTrue(ctx, hintsEnv) +} + +func envTrue(ctx context.Context, key string) bool { + on, _ := env.GetBool(ctx, key) + return on +} diff --git a/libs/skills/guard_test.go b/libs/skills/guard_test.go new file mode 100644 index 00000000000..6d0950df76a --- /dev/null +++ b/libs/skills/guard_test.go @@ -0,0 +1,64 @@ +package skills + +import ( + "testing" + + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" +) + +func TestEnabled(t *testing.T) { + cases := []struct { + name string + value string + set bool + want bool + }{ + {name: "unset", want: false}, + {name: "true", set: true, value: "true", want: true}, + {name: "one", set: true, value: "1", want: true}, + {name: "false", set: true, value: "false", want: false}, + {name: "zero", set: true, value: "0", want: false}, + {name: "empty", set: true, value: "", want: false}, + {name: "invalid", set: true, value: "maybe", want: false}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + ctx := t.Context() + if c.set { + ctx = env.Set(ctx, "DATABRICKS_SKILLS_PREVIEW", c.value) + } + assert.Equal(t, c.want, Enabled(ctx)) + }) + } +} + +func TestHintsEnabled(t *testing.T) { + cases := []struct { + name string + preview string + hints string + want bool + }{ + {name: "both unset", want: false}, + {name: "preview off, hints on", preview: "false", hints: "true", want: false}, + {name: "preview unset, hints on", hints: "true", want: false}, + {name: "preview on, hints unset", preview: "true", want: false}, + {name: "preview on, hints false", preview: "true", hints: "false", want: false}, + {name: "preview on, hints invalid", preview: "true", hints: "maybe", want: false}, + {name: "preview on, hints true", preview: "true", hints: "true", want: true}, + {name: "preview on, hints one", preview: "1", hints: "1", want: true}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + ctx := t.Context() + if c.preview != "" { + ctx = env.Set(ctx, "DATABRICKS_SKILLS_PREVIEW", c.preview) + } + if c.hints != "" { + ctx = env.Set(ctx, "DATABRICKS_SKILLS_HINTS", c.hints) + } + assert.Equal(t, c.want, HintsEnabled(ctx)) + }) + } +} diff --git a/libs/skills/resolve.go b/libs/skills/resolve.go new file mode 100644 index 00000000000..44d23dde366 --- /dev/null +++ b/libs/skills/resolve.go @@ -0,0 +1,40 @@ +package skills + +import ( + "context" + "errors" + "os" + + "github.com/databricks/cli/libs/env" +) + +// dirEnv names a folder that holds a skills release. It is read before any +// other source, so a developer can point the CLI at a local copy. +const dirEnv = "DATABRICKS_SKILLS_DIR" + +// ErrNoSource reports that this build has no skills source to read from. +var ErrNoSource = errors.New("no skills source is available in this build") + +// Resolve returns the source that serves skills. For now that is the folder in +// DATABRICKS_SKILLS_DIR, when it is set. Otherwise no source is available. +func Resolve(ctx context.Context) (Source, error) { + dir := env.Get(ctx, dirEnv) + if dir == "" { + return nil, ErrNoSource + } + return NewFSSource(os.DirFS(dir), dir), nil +} + +// LocalCatalog returns the freshest catalog that needs no network call. For now +// that is the folder in DATABRICKS_SKILLS_DIR. It returns nil when no folder is +// set. +func LocalCatalog(ctx context.Context) (*Catalog, error) { + if env.Get(ctx, dirEnv) == "" { + return nil, nil + } + src, err := Resolve(ctx) + if err != nil { + return nil, err + } + return src.Catalog(ctx) +} diff --git a/libs/skills/resolve_test.go b/libs/skills/resolve_test.go new file mode 100644 index 00000000000..ee6641db46a --- /dev/null +++ b/libs/skills/resolve_test.go @@ -0,0 +1,43 @@ +package skills + +import ( + "path/filepath" + "testing" + + "github.com/databricks/cli/libs/env" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestResolveWithoutDir(t *testing.T) { + src, err := Resolve(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", "")) + assert.ErrorIs(t, err, ErrNoSource) + assert.Nil(t, src) +} + +func TestResolveWithDir(t *testing.T) { + ctx := env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", "testdata/release") + src, err := Resolve(ctx) + require.NoError(t, err) + + catalog, err := src.Catalog(ctx) + require.NoError(t, err) + assert.Equal(t, "1.2.0", catalog.Version) + assert.Equal(t, "testdata/release", catalog.Label) +} + +func TestLocalCatalogWithoutDir(t *testing.T) { + catalog, err := LocalCatalog(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", "")) + assert.NoError(t, err) + assert.Nil(t, catalog) +} + +// The acceptance fixture is the release that later acceptance tests point +// DATABRICKS_SKILLS_DIR at, so this checks that it stays a valid release. +func TestLocalCatalogFromAcceptanceFixture(t *testing.T) { + dir := filepath.Join("..", "..", "acceptance", "cmd", "skills", "release") + catalog, err := LocalCatalog(env.Set(t.Context(), "DATABRICKS_SKILLS_DIR", dir)) + require.NoError(t, err) + require.Len(t, catalog.Skills, 1) + assert.Equal(t, "demo-skill", catalog.Skills[0].Name) +} From fcd2902e3ad98234c000c55a3bec40ba6c4017b7 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 10:15:21 +0000 Subject: [PATCH 14/25] Check skills command name against root commands, clear env in guard tests Check the skills group in the root command uniqueness test, even though it is registered only behind DATABRICKS_SKILLS_PREVIEW. Clear both guard variables in the guard tests so an exported value does not leak in. LocalCatalog calls Resolve first and maps ErrNoSource to no catalog. Route the acceptance help check to LOG.help. Co-authored-by: Isaac --- acceptance/cmd/skills/disabled/script | 5 +++-- acceptance/cmd/skills/enabled/script | 2 +- cmd/cmd_test.go | 7 +++++- libs/skills/guard_test.go | 32 +++++++++++---------------- libs/skills/resolve.go | 4 ++-- 5 files changed, 25 insertions(+), 25 deletions(-) diff --git a/acceptance/cmd/skills/disabled/script b/acceptance/cmd/skills/disabled/script index f06f9b1b9fd..7d1ebd5473a 100644 --- a/acceptance/cmd/skills/disabled/script +++ b/acceptance/cmd/skills/disabled/script @@ -1,3 +1,4 @@ -# Unset, the skills group is not registered: it is an unknown command and is not listed in help. +# Unset, the skills group is not registered: it is an unknown command. musterr trace env -u DATABRICKS_SKILLS_PREVIEW $CLI skills list -trace env -u DATABRICKS_SKILLS_PREVIEW $CLI --help | contains.py "! skills " > /dev/null +# The group is hidden, so this only checks the help text. The gate is the line above. +trace env -u DATABRICKS_SKILLS_PREVIEW $CLI --help | contains.py "! skills " > LOG.help diff --git a/acceptance/cmd/skills/enabled/script b/acceptance/cmd/skills/enabled/script index ebd3804ae95..7ddfc3feae6 100644 --- a/acceptance/cmd/skills/enabled/script +++ b/acceptance/cmd/skills/enabled/script @@ -1,6 +1,6 @@ # With the variable set, the group lists its five subcommands and stays hidden from the root help. trace $CLI skills --help -trace $CLI --help | contains.py "! skills " > /dev/null +trace $CLI --help | contains.py "! skills " > LOG.help # Each subcommand is a stub that exits non-zero with the not-implemented message. musterr trace $CLI skills list diff --git a/cmd/cmd_test.go b/cmd/cmd_test.go index 3f488deb907..d1eae15d04b 100644 --- a/cmd/cmd_test.go +++ b/cmd/cmd_test.go @@ -3,12 +3,17 @@ package cmd import ( "testing" + skillscmd "github.com/databricks/cli/cmd/skills" "github.com/stretchr/testify/assert" ) func TestRootCommandNamesAreUnique(t *testing.T) { seen := map[string]bool{} - for _, spec := range topLevelSpecs() { + // The skills group is registered only behind DATABRICKS_SKILLS_PREVIEW, so + // it is not in topLevelSpecs. It is checked here anyway, so a clash with a + // workspace command is caught while the variable is off. + specs := append(topLevelSpecs(), skillscmd.Spec) + for _, spec := range specs { assert.False(t, seen[spec.Name()], "duplicate top-level command %q", spec.Name()) seen[spec.Name()] = true } diff --git a/libs/skills/guard_test.go b/libs/skills/guard_test.go index 6d0950df76a..49a2889a2fd 100644 --- a/libs/skills/guard_test.go +++ b/libs/skills/guard_test.go @@ -7,27 +7,26 @@ import ( "github.com/stretchr/testify/assert" ) +// Each case sets both variables in the context, with "" for unset. env.Get +// reads the context first, so an exported DATABRICKS_SKILLS_PREVIEW or +// DATABRICKS_SKILLS_HINTS on the developer's machine does not leak in. func TestEnabled(t *testing.T) { cases := []struct { name string value string - set bool want bool }{ - {name: "unset", want: false}, - {name: "true", set: true, value: "true", want: true}, - {name: "one", set: true, value: "1", want: true}, - {name: "false", set: true, value: "false", want: false}, - {name: "zero", set: true, value: "0", want: false}, - {name: "empty", set: true, value: "", want: false}, - {name: "invalid", set: true, value: "maybe", want: false}, + {name: "unset", value: "", want: false}, + {name: "true", value: "true", want: true}, + {name: "one", value: "1", want: true}, + {name: "false", value: "false", want: false}, + {name: "zero", value: "0", want: false}, + {name: "empty", value: "", want: false}, + {name: "invalid", value: "maybe", want: false}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - ctx := t.Context() - if c.set { - ctx = env.Set(ctx, "DATABRICKS_SKILLS_PREVIEW", c.value) - } + ctx := env.Set(t.Context(), "DATABRICKS_SKILLS_PREVIEW", c.value) assert.Equal(t, c.want, Enabled(ctx)) }) } @@ -51,13 +50,8 @@ func TestHintsEnabled(t *testing.T) { } for _, c := range cases { t.Run(c.name, func(t *testing.T) { - ctx := t.Context() - if c.preview != "" { - ctx = env.Set(ctx, "DATABRICKS_SKILLS_PREVIEW", c.preview) - } - if c.hints != "" { - ctx = env.Set(ctx, "DATABRICKS_SKILLS_HINTS", c.hints) - } + ctx := env.Set(t.Context(), "DATABRICKS_SKILLS_PREVIEW", c.preview) + ctx = env.Set(ctx, "DATABRICKS_SKILLS_HINTS", c.hints) assert.Equal(t, c.want, HintsEnabled(ctx)) }) } diff --git a/libs/skills/resolve.go b/libs/skills/resolve.go index 44d23dde366..8cc026e3d8b 100644 --- a/libs/skills/resolve.go +++ b/libs/skills/resolve.go @@ -29,10 +29,10 @@ func Resolve(ctx context.Context) (Source, error) { // that is the folder in DATABRICKS_SKILLS_DIR. It returns nil when no folder is // set. func LocalCatalog(ctx context.Context) (*Catalog, error) { - if env.Get(ctx, dirEnv) == "" { + src, err := Resolve(ctx) + if errors.Is(err, ErrNoSource) { return nil, nil } - src, err := Resolve(ctx) if err != nil { return nil, err } From 497ff28e9314ae7ac01deb700a00ef3f3b4b7f6c Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 10:17:03 +0000 Subject: [PATCH 15/25] Print the skills catalog from skills list Text output shows the catalog rules, then one line per skill with its description cut to fit a fixed budget, then how to read a skill. JSON output carries the full catalog with empty lists as []. Experimental skills are listed only with --experimental. Co-authored-by: Isaac --- acceptance/cmd/skills/list/output.txt | 2 +- cmd/skills/list.go | 12 ++++++++++-- cmd/skills/list_test.go | 12 ++++++------ 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/acceptance/cmd/skills/list/output.txt b/acceptance/cmd/skills/list/output.txt index 1eef79d126c..2326cc259cb 100644 --- a/acceptance/cmd/skills/list/output.txt +++ b/acceptance/cmd/skills/list/output.txt @@ -56,7 +56,7 @@ To read a skill, run: databricks skills read "files": [ "SKILL.md" ], - "commands": null + "commands": [] } ] } diff --git a/cmd/skills/list.go b/cmd/skills/list.go index 30c40069490..fc6737bc153 100644 --- a/cmd/skills/list.go +++ b/cmd/skills/list.go @@ -165,6 +165,14 @@ type listJSONSkill struct { Commands []string `json:"commands"` } +// nonNilList keeps an absent list as [] in JSON rather than null. +func nonNilList(list []string) []string { + if list == nil { + return make([]string, 0) + } + return list +} + func writeListJSON(w io.Writer, catalog *libskills.Catalog, list []libskills.Skill) error { out := listJSON{ Source: catalog.Label, @@ -176,8 +184,8 @@ func writeListJSON(w io.Writer, catalog *libskills.Catalog, list []libskills.Ski Name: s.Name, Description: s.Description, Version: s.Version, - Files: s.Files, - Commands: s.Commands, + Files: nonNilList(s.Files), + Commands: nonNilList(s.Commands), }) } enc := json.NewEncoder(w) diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index 01e34682e11..42900f000d3 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -16,15 +16,15 @@ import ( "github.com/stretchr/testify/require" ) -type fakeSource struct { +type listFakeSource struct { catalog *libskills.Catalog } -func (f fakeSource) Catalog(context.Context) (*libskills.Catalog, error) { +func (f listFakeSource) Catalog(context.Context) (*libskills.Catalog, error) { return f.catalog, nil } -func (f fakeSource) ReadFile(context.Context, string, string) ([]byte, error) { +func (f listFakeSource) ReadFile(context.Context, string, string) ([]byte, error) { return nil, libskills.ErrUnknownFile } @@ -141,12 +141,12 @@ func TestRunListTextAndJSON(t *testing.T) { } cmd, stdout, stderr := listTestCmd(t, flags.OutputText) - require.NoError(t, runList(cmd, fakeSource{catalog}, false)) + require.NoError(t, runList(cmd, listFakeSource{catalog}, false)) assert.Equal(t, "alpha: First.\nbeta: Second.\n"+readHint+"\n", stdout.String()) assert.Empty(t, stderr.String()) cmd, stdout, _ = listTestCmd(t, flags.OutputJSON) - require.NoError(t, runList(cmd, fakeSource{catalog}, false)) + require.NoError(t, runList(cmd, listFakeSource{catalog}, false)) var got struct { Source string `json:"source"` ReleaseVersion string `json:"release_version"` @@ -176,7 +176,7 @@ func TestRunListStaleCatalogPrintsProvenanceOnStderr(t *testing.T) { } cmd, stdout, stderr := listTestCmd(t, flags.OutputText) - require.NoError(t, runList(cmd, fakeSource{catalog}, false)) + require.NoError(t, runList(cmd, listFakeSource{catalog}, false)) assert.Contains(t, stderr.String(), "Skills come from cached (release 1.2.3, fetched 2026-11-01T00:00:00Z)") assert.NotContains(t, stdout.String(), "Skills come from") } From 4844df83c6db8c5b50f08251947ed11b1e0031b8 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 10:59:45 +0000 Subject: [PATCH 16/25] Keep skills list text within the budget and route its JSON through cmdio Stop the description search at the narrowest width that keeps the first word of every description, so no line is left as "name: ...". Print the "left out" hint only when a description is actually left out. Render the JSON through cmdio.Render like other commands, and drop the unit test that duplicated the acceptance output. The list keeps the order the source serves, which is sorted by name. Co-authored-by: Isaac --- cmd/skills/list.go | 60 +++++++++++++++++++++++------------ cmd/skills/list_test.go | 69 ++++++++++++++++------------------------- 2 files changed, 68 insertions(+), 61 deletions(-) diff --git a/cmd/skills/list.go b/cmd/skills/list.go index fc6737bc153..06cedfea53a 100644 --- a/cmd/skills/list.go +++ b/cmd/skills/list.go @@ -1,7 +1,6 @@ package skills import ( - "encoding/json" "fmt" "io" "slices" @@ -9,6 +8,7 @@ import ( "time" "github.com/databricks/cli/cmd/root" + "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/flags" libskills "github.com/databricks/cli/libs/skills" "github.com/spf13/cobra" @@ -52,14 +52,14 @@ func runList(cmd *cobra.Command, src libskills.Source, experimental bool) error list := visibleSkills(catalog.Skills, experimental) if root.OutputType(cmd) == flags.OutputJSON { - return writeListJSON(cmd.OutOrStdout(), catalog, list) + return cmdio.Render(cmd.Context(), newListJSON(catalog, list)) } _, err = io.WriteString(cmd.OutOrStdout(), renderText(catalog.Rules, list)) return err } -// visibleSkills returns the skills to list, sorted by name so that the order -// is the same on every run. Experimental skills are left out unless asked for. +// visibleSkills returns the skills to list in the order the source serves them, +// which is sorted by name. Experimental skills are left out unless asked for. func visibleSkills(all []libskills.Skill, experimental bool) []libskills.Skill { var list []libskills.Skill for _, s := range all { @@ -68,9 +68,6 @@ func visibleSkills(all []libskills.Skill, experimental bool) []libskills.Skill { } list = append(list, s) } - slices.SortFunc(list, func(a, b libskills.Skill) int { - return strings.Compare(a.Name, b.Name) - }) return list } @@ -94,8 +91,13 @@ func renderText(rules string, list []libskills.Skill) string { if full := layoutText(rules, list, maxLen); len(full) <= textBudget { return full } - // Find the widest width in [0, maxLen-1] that fits. Width 0 lists names only. - lo, hi := 0, maxLen-1 + // Below the floor some description would be cut to "..." alone, so the + // search for the widest fitting width starts at the floor. + floor := narrowestKeepingWords(list, maxLen) + if len(layoutText(rules, list, floor)) > textBudget { + return layoutText(rules, list, 0) + } + lo, hi := floor, maxLen for lo < hi { mid := (lo + hi + 1) / 2 if len(layoutText(rules, list, mid)) <= textBudget { @@ -107,22 +109,44 @@ func renderText(rules string, list []libskills.Skill) string { return layoutText(rules, list, lo) } +// narrowestKeepingWords returns the narrowest width, at most maxLen, at which +// cutting every description keeps at least its first word. +func narrowestKeepingWords(list []libskills.Skill, maxLen int) int { + lo, hi := 1, max(maxLen, 1) + for lo < hi { + mid := (lo + hi) / 2 + if keepsFirstWords(list, mid) { + hi = mid + } else { + lo = mid + 1 + } + } + return lo +} + +// keepsFirstWords reports whether no description is cut to "..." alone at width. +func keepsFirstWords(list []libskills.Skill, width int) bool { + for _, s := range list { + if len(s.Description) > width && cutWords(s.Description, width) == "..." { + return false + } + } + return true +} + // layoutText lays out the text output with descriptions cut to width. A width // of 0 leaves the descriptions out. func layoutText(rules string, list []libskills.Skill, width int) string { var b strings.Builder b.WriteString(withRules(rules)) for _, s := range list { - switch { - case width == 0: - b.WriteString(s.Name + "\n") - case s.Description == "": + if width == 0 || s.Description == "" { b.WriteString(s.Name + "\n") - default: + } else { fmt.Fprintf(&b, "%s: %s\n", s.Name, cutWords(s.Description, width)) } } - if width == 0 { + if width == 0 && slices.ContainsFunc(list, func(s libskills.Skill) bool { return s.Description != "" }) { b.WriteString(searchHint + "\n") } b.WriteString(readHint + "\n") @@ -173,7 +197,7 @@ func nonNilList(list []string) []string { return list } -func writeListJSON(w io.Writer, catalog *libskills.Catalog, list []libskills.Skill) error { +func newListJSON(catalog *libskills.Catalog, list []libskills.Skill) listJSON { out := listJSON{ Source: catalog.Label, ReleaseVersion: catalog.Version, @@ -188,7 +212,5 @@ func writeListJSON(w io.Writer, catalog *libskills.Catalog, list []libskills.Ski Commands: nonNilList(s.Commands), }) } - enc := json.NewEncoder(w) - enc.SetIndent("", " ") - return enc.Encode(out) + return out } diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index 42900f000d3..b4a4d203300 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -3,7 +3,6 @@ package skills import ( "bytes" "context" - "encoding/json" "fmt" "strings" "testing" @@ -59,7 +58,7 @@ func TestRenderTextFortySkillsFitsBudget(t *testing.T) { assert.LessOrEqual(t, len(out), textBudget) for _, s := range list { - assert.Contains(t, out, s.Name+": ") + assert.Contains(t, out, s.Name+": "+strings.Fields(s.Description)[0]) } assert.True(t, strings.HasPrefix(out, "Pick the skill whose description matches the task.\n\n")) assert.True(t, strings.HasSuffix(out, readHint+"\n")) @@ -92,6 +91,29 @@ func TestRenderTextNamesOnlyWhenNamesExceedBudget(t *testing.T) { assert.Contains(t, out, readHint) } +func TestRenderTextNeverCutsDescriptionToNothing(t *testing.T) { + var list []libskills.Skill + for i := range 130 { + list = append(list, libskills.Skill{ + Name: fmt.Sprintf("skill-%014d", i), + Description: "Deploys the workspace resources, then reports every step taken and any error found.", + }) + } + out := renderText("", list) + + assert.LessOrEqual(t, len(out), textBudget) + assert.NotContains(t, out, ": ...\n") + for _, s := range list { + assert.Contains(t, out, s.Name+"\n") + } + assert.Contains(t, out, "databricks skills search ") +} + +func TestRenderTextNoSearchHintWithoutDescriptions(t *testing.T) { + list := []libskills.Skill{{Name: "alpha"}, {Name: "beta"}} + assert.Equal(t, "alpha\nbeta\n"+readHint+"\n", renderText("", list)) +} + func TestRenderTextNoSkills(t *testing.T) { assert.Equal(t, "No skills found.\n", renderText("", nil)) } @@ -115,11 +137,11 @@ func TestCutWords(t *testing.T) { } } -func TestVisibleSkillsSortsAndHidesExperimental(t *testing.T) { +func TestVisibleSkillsHidesExperimentalKeepsOrder(t *testing.T) { all := []libskills.Skill{ - {Name: "zeta"}, - {Name: "preview", Experimental: true}, {Name: "alpha"}, + {Name: "preview", Experimental: true}, + {Name: "zeta"}, } stable := visibleSkills(all, false) @@ -129,43 +151,6 @@ func TestVisibleSkillsSortsAndHidesExperimental(t *testing.T) { assert.Equal(t, []string{"alpha", "preview", "zeta"}, names(withExperimental)) } -func TestRunListTextAndJSON(t *testing.T) { - catalog := &libskills.Catalog{ - Label: "test", - Version: "1.2.3", - FetchedAt: time.Now(), - Skills: []libskills.Skill{ - {Name: "beta", Description: "Second.", Version: "0.1", Files: []string{"SKILL.md"}, Commands: []string{"jobs"}}, - {Name: "alpha", Description: "First.", Version: "0.2", Files: []string{"SKILL.md"}}, - }, - } - - cmd, stdout, stderr := listTestCmd(t, flags.OutputText) - require.NoError(t, runList(cmd, listFakeSource{catalog}, false)) - assert.Equal(t, "alpha: First.\nbeta: Second.\n"+readHint+"\n", stdout.String()) - assert.Empty(t, stderr.String()) - - cmd, stdout, _ = listTestCmd(t, flags.OutputJSON) - require.NoError(t, runList(cmd, listFakeSource{catalog}, false)) - var got struct { - Source string `json:"source"` - ReleaseVersion string `json:"release_version"` - Skills []struct { - Name string `json:"name"` - Version string `json:"version"` - Files []string `json:"files"` - Commands []string `json:"commands"` - } `json:"skills"` - } - require.NoError(t, json.Unmarshal(stdout.Bytes(), &got)) - assert.Equal(t, "test", got.Source) - assert.Equal(t, "1.2.3", got.ReleaseVersion) - require.Len(t, got.Skills, 2) - assert.Equal(t, "alpha", got.Skills[0].Name) - assert.Equal(t, "beta", got.Skills[1].Name) - assert.Equal(t, []string{"jobs"}, got.Skills[1].Commands) -} - func TestRunListStaleCatalogPrintsProvenanceOnStderr(t *testing.T) { catalog := &libskills.Catalog{ Label: "cached", From 672993327f30b3ee8cb0593ca1c245352e29261a Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 12:59:00 +0000 Subject: [PATCH 17/25] Update agent-hints acceptance test for implemented skills list skills list now runs, so the test's skills list call fails with the no-source error instead of the not-implemented stub message. The test only checks that no hint is printed, so update the comment and golden. Co-authored-by: Isaac --- acceptance/cmd/aitools/agent-hints/output.txt | 2 +- acceptance/cmd/aitools/agent-hints/script | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/acceptance/cmd/aitools/agent-hints/output.txt b/acceptance/cmd/aitools/agent-hints/output.txt index 273babf77ce..7ddfc4ab9e9 100644 --- a/acceptance/cmd/aitools/agent-hints/output.txt +++ b/acceptance/cmd/aitools/agent-hints/output.txt @@ -52,4 +52,4 @@ Before you work with Databricks, run: databricks skills list === With skill hints on, skills commands print no hint >>> DATABRICKS_SKILLS_PREVIEW=1 DATABRICKS_SKILLS_HINTS=1 CODEX_CI=1 CODEX_THREAD_ID=thread-5 [CLI] skills list -Error: databricks skills list is not implemented yet +Error: no skills source is available in this build diff --git a/acceptance/cmd/aitools/agent-hints/script b/acceptance/cmd/aitools/agent-hints/script index 071bb29b5d2..1f993a5e6e0 100644 --- a/acceptance/cmd/aitools/agent-hints/script +++ b/acceptance/cmd/aitools/agent-hints/script @@ -38,7 +38,7 @@ title "With skill hints on, Cursor is hinted once per machine with the skills li trace DATABRICKS_SKILLS_PREVIEW=1 DATABRICKS_SKILLS_HINTS=1 CURSOR_AGENT=1 $CLI jobs list trace DATABRICKS_SKILLS_PREVIEW=1 DATABRICKS_SKILLS_HINTS=1 CURSOR_AGENT=1 $CLI jobs list -# The skills subcommands are stubs until their own changes land, so `skills list` -# fails with its not-implemented message; the point is that it prints no hint. +# This build has no skills source, so `skills list` fails with its no-source +# error; the point is that it prints no hint. title "With skill hints on, skills commands print no hint" musterr trace DATABRICKS_SKILLS_PREVIEW=1 DATABRICKS_SKILLS_HINTS=1 CODEX_CI=1 CODEX_THREAD_ID=thread-5 $CLI skills list From b10ce6ad276dc3c2de746d345443cf9605618470 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 13:27:16 +0000 Subject: [PATCH 18/25] Keep skills list acceptance in step with merged siblings Drop the enabled script's stubs for list-files and read-file, which are implemented now, and remove the unused notImplemented helper. Regenerate the list golden for the release fixture's demo-skill commands. Co-authored-by: Isaac --- acceptance/cmd/skills/enabled/output.txt | 6 ------ acceptance/cmd/skills/list/output.txt | 6 ++++-- cmd/skills/skills.go | 7 ------- 3 files changed, 4 insertions(+), 15 deletions(-) diff --git a/acceptance/cmd/skills/enabled/output.txt b/acceptance/cmd/skills/enabled/output.txt index 1a547e32ada..c198d2a0f9e 100644 --- a/acceptance/cmd/skills/enabled/output.txt +++ b/acceptance/cmd/skills/enabled/output.txt @@ -24,9 +24,3 @@ Global Flags: Use "databricks skills [command] --help" for more information about a command. >>> [CLI] --help - ->>> [CLI] skills list-files demo-skill -Error: databricks skills list-files is not implemented yet - ->>> [CLI] skills read-file demo-skill SKILL.md -Error: databricks skills read-file is not implemented yet diff --git a/acceptance/cmd/skills/list/output.txt b/acceptance/cmd/skills/list/output.txt index fe8d839937a..5f1850dd791 100644 --- a/acceptance/cmd/skills/list/output.txt +++ b/acceptance/cmd/skills/list/output.txt @@ -31,7 +31,8 @@ To read a skill, run: databricks skills read "SKILL.md" ], "commands": [ - "jobs" + "fs", + "air" ] }, { @@ -69,7 +70,8 @@ To read a skill, run: databricks skills read "SKILL.md" ], "commands": [ - "jobs" + "fs", + "air" ] }, { diff --git a/cmd/skills/skills.go b/cmd/skills/skills.go index 963add4ee16..25185cdbc54 100644 --- a/cmd/skills/skills.go +++ b/cmd/skills/skills.go @@ -4,7 +4,6 @@ package skills import ( "context" - "fmt" "github.com/databricks/cli/cmd/root" "github.com/spf13/cobra" @@ -25,9 +24,3 @@ func buildCommand(_ context.Context, cmd *cobra.Command) { cmd.AddCommand(newReadFileCmd()) cmd.AddCommand(newSearchCmd()) } - -// notImplemented is the run function of every subcommand until its own change -// lands. -func notImplemented(cmd *cobra.Command, _ []string) error { - return fmt.Errorf("%s is not implemented yet", cmd.CommandPath()) -} From c4a5e802d79c7743a06a885b62366f900a59179e Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 14:03:35 +0000 Subject: [PATCH 19/25] Keep each skills list description within the text budget - Cut each description at a word boundary. A skill whose description has no boundary within the width is listed by name alone, so one long description does not drop the rest of the catalog. - Collapse whitespace in text output so every skill takes one line. - Print the provenance line through cmdio.LogString, and leave out the fetch time when it is unknown, as for a bundled copy. - Use forward slashes in the JSON source label, as skills search does. - Hint at --experimental when every skill is experimental. - Drop the acceptance test.toml that repeats the parent's settings. Co-authored-by: Isaac --- acceptance/cmd/skills/list/test.toml | 2 - cmd/skills/list.go | 94 ++++++++++++++-------------- cmd/skills/list_test.go | 46 ++++++++++++-- 3 files changed, 87 insertions(+), 55 deletions(-) delete mode 100644 acceptance/cmd/skills/list/test.toml diff --git a/acceptance/cmd/skills/list/test.toml b/acceptance/cmd/skills/list/test.toml deleted file mode 100644 index 27401a415e2..00000000000 --- a/acceptance/cmd/skills/list/test.toml +++ /dev/null @@ -1,2 +0,0 @@ -Cloud = false -Env.DATABRICKS_SKILLS_PREVIEW = "1" diff --git a/cmd/skills/list.go b/cmd/skills/list.go index 06cedfea53a..54017c1a6e5 100644 --- a/cmd/skills/list.go +++ b/cmd/skills/list.go @@ -3,7 +3,7 @@ package skills import ( "fmt" "io" - "slices" + "path/filepath" "strings" "time" @@ -14,13 +14,14 @@ import ( "github.com/spf13/cobra" ) -// textBudget is the most characters the text output of `skills list` may have. +// textBudget is the most bytes the text output of `skills list` may have. // Descriptions are cut to fit it, so an agent sees the whole catalog at once. const textBudget = 4000 const ( - readHint = "To read a skill, run: databricks skills read " - searchHint = "Descriptions are left out to fit the output. To find a skill, run: databricks skills search " + readHint = "To read a skill, run: databricks skills read " + searchHint = "Descriptions are left out to fit the output. To find a skill, run: databricks skills search " + experimentalHint = "Experimental skills are hidden. To list them, run: databricks skills list --experimental" ) func newListCmd() *cobra.Command { @@ -47,14 +48,19 @@ func runList(cmd *cobra.Command, src libskills.Source, experimental bool) error return err } if catalog.Stale { - fmt.Fprintln(cmd.ErrOrStderr(), provenanceLine(catalog)) + cmdio.LogString(cmd.Context(), provenanceLine(catalog)) } list := visibleSkills(catalog.Skills, experimental) if root.OutputType(cmd) == flags.OutputJSON { return cmdio.Render(cmd.Context(), newListJSON(catalog, list)) } - _, err = io.WriteString(cmd.OutOrStdout(), renderText(catalog.Rules, list)) + text := renderText(catalog.Rules, list) + if len(list) == 0 && len(catalog.Skills) > 0 { + // Every skill is experimental, so an agent would otherwise read "No skills found." + text += experimentalHint + "\n" + } + _, err = io.WriteString(cmd.OutOrStdout(), text) return err } @@ -71,9 +77,16 @@ func visibleSkills(all []libskills.Skill, experimental bool) []libskills.Skill { return list } +// provenanceLine says where a stale catalog came from. A bundled copy has no +// fetch time, so the line leaves it out rather than print the zero time. func provenanceLine(catalog *libskills.Catalog) string { + label := filepath.ToSlash(catalog.Label) + if catalog.FetchedAt.IsZero() { + return fmt.Sprintf("Skills come from %s (release %s). The source could not be refreshed, so the list may be out of date.", + label, catalog.Version) + } return fmt.Sprintf("Skills come from %s (release %s, fetched %s). The source could not be refreshed, so the list may be out of date.", - catalog.Label, catalog.Version, catalog.FetchedAt.Format(time.RFC3339)) + label, catalog.Version, catalog.FetchedAt.Format(time.RFC3339)) } // renderText returns the text output of `skills list`: the catalog rules, then @@ -86,18 +99,14 @@ func renderText(rules string, list []libskills.Skill) string { } maxLen := 0 for _, s := range list { - maxLen = max(maxLen, len(s.Description)) + maxLen = max(maxLen, len(oneLine(s.Description))) } if full := layoutText(rules, list, maxLen); len(full) <= textBudget { return full } - // Below the floor some description would be cut to "..." alone, so the - // search for the widest fitting width starts at the floor. - floor := narrowestKeepingWords(list, maxLen) - if len(layoutText(rules, list, floor)) > textBudget { - return layoutText(rules, list, 0) - } - lo, hi := floor, maxLen + // Width 0 leaves every description out, so it is the answer when the names + // alone do not fit. + lo, hi := 0, maxLen for lo < hi { mid := (lo + hi + 1) / 2 if len(layoutText(rules, list, mid)) <= textBudget { @@ -109,50 +118,40 @@ func renderText(rules string, list []libskills.Skill) string { return layoutText(rules, list, lo) } -// narrowestKeepingWords returns the narrowest width, at most maxLen, at which -// cutting every description keeps at least its first word. -func narrowestKeepingWords(list []libskills.Skill, maxLen int) int { - lo, hi := 1, max(maxLen, 1) - for lo < hi { - mid := (lo + hi) / 2 - if keepsFirstWords(list, mid) { - hi = mid - } else { - lo = mid + 1 - } - } - return lo -} - -// keepsFirstWords reports whether no description is cut to "..." alone at width. -func keepsFirstWords(list []libskills.Skill, width int) bool { - for _, s := range list { - if len(s.Description) > width && cutWords(s.Description, width) == "..." { - return false - } - } - return true -} - // layoutText lays out the text output with descriptions cut to width. A width -// of 0 leaves the descriptions out. +// of 0 leaves every description out. A skill is listed by its name alone when +// its description is left out or has no word boundary within width, so one +// long description does not drop the others. func layoutText(rules string, list []libskills.Skill, width int) string { var b strings.Builder b.WriteString(withRules(rules)) + dropped := false for _, s := range list { - if width == 0 || s.Description == "" { + desc := oneLine(s.Description) + cut := "" + if width > 0 { + cut = cutWords(desc, width) + } + if cut == "" { b.WriteString(s.Name + "\n") + dropped = dropped || desc != "" } else { - fmt.Fprintf(&b, "%s: %s\n", s.Name, cutWords(s.Description, width)) + fmt.Fprintf(&b, "%s: %s\n", s.Name, cut) } } - if width == 0 && slices.ContainsFunc(list, func(s libskills.Skill) bool { return s.Description != "" }) { + if dropped { b.WriteString(searchHint + "\n") } b.WriteString(readHint + "\n") return b.String() } +// oneLine joins the words of s with single spaces, so a description takes +// exactly one line of output. +func oneLine(s string) string { + return strings.Join(strings.Fields(s), " ") +} + func withRules(rules string) string { rules = strings.TrimSpace(rules) if rules == "" { @@ -162,7 +161,8 @@ func withRules(rules string) string { } // cutWords returns desc unchanged when it fits in width. Otherwise it cuts desc -// at the last word boundary that leaves room for "..." within width. +// at the last word boundary that leaves room for "..." within width. It returns +// "" when there is no such boundary. func cutWords(desc string, width int) string { if len(desc) <= width { return desc @@ -172,7 +172,7 @@ func cutWords(desc string, width int) string { return desc[:i] + "..." } } - return "..." + return "" } type listJSON struct { @@ -199,7 +199,7 @@ func nonNilList(list []string) []string { func newListJSON(catalog *libskills.Catalog, list []libskills.Skill) listJSON { out := listJSON{ - Source: catalog.Label, + Source: filepath.ToSlash(catalog.Label), ReleaseVersion: catalog.Version, Skills: make([]listJSONSkill, 0, len(list)), } diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index b4a4d203300..83177f07817 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -8,6 +8,7 @@ import ( "testing" "time" + "github.com/databricks/cli/libs/cmdio" "github.com/databricks/cli/libs/flags" libskills "github.com/databricks/cli/libs/skills" "github.com/spf13/cobra" @@ -27,16 +28,18 @@ func (f listFakeSource) ReadFile(context.Context, string, string) ([]byte, error return nil, libskills.ErrUnknownFile } +// listTestCmd returns a command with the root's output flag, whose context +// captures stderr, and the buffer that captures stdout. func listTestCmd(t *testing.T, output flags.Output) (*cobra.Command, *bytes.Buffer, *bytes.Buffer) { t.Helper() + ctx, stderr := cmdio.NewTestContextWithStderr(t.Context()) cmd := &cobra.Command{} - cmd.SetContext(t.Context()) + cmd.SetContext(ctx) out := output cmd.Flags().Var(&out, "output", "") - var stdout, stderr bytes.Buffer + var stdout bytes.Buffer cmd.SetOut(&stdout) - cmd.SetErr(&stderr) - return cmd, &stdout, &stderr + return cmd, &stdout, stderr } // longSkills returns n skills whose descriptions are far longer than the budget @@ -74,6 +77,11 @@ func TestRenderTextKeepsFullDescriptionsWhenTheyFit(t *testing.T) { assert.Equal(t, "alpha: Alpha does one thing well.\nbeta: Beta does another.\n"+readHint+"\n", out) } +func TestRenderTextKeepsOneLinePerSkill(t *testing.T) { + list := []libskills.Skill{{Name: "alpha", Description: "Line one.\nLine two.\tTabbed text."}} + assert.Equal(t, "alpha: Line one. Line two. Tabbed text.\n"+readHint+"\n", renderText("", list)) +} + func TestRenderTextNamesOnlyWhenNamesExceedBudget(t *testing.T) { var list []libskills.Skill for i := range 400 { @@ -109,6 +117,18 @@ func TestRenderTextNeverCutsDescriptionToNothing(t *testing.T) { assert.Contains(t, out, "databricks skills search ") } +func TestRenderTextOneUnbreakableDescriptionDropsOnlyItself(t *testing.T) { + list := visibleSkills(longSkills(40), false) + list = append(list, libskills.Skill{Name: "blob", Description: strings.Repeat("x", 300)}) + + out := renderText("", list) + + assert.LessOrEqual(t, len(out), textBudget) + assert.Contains(t, out, "\nblob\n") + assert.Contains(t, out, "skill-39: word39 ") + assert.Contains(t, out, "databricks skills search ") +} + func TestRenderTextNoSearchHintWithoutDescriptions(t *testing.T) { list := []libskills.Skill{{Name: "alpha"}, {Name: "beta"}} assert.Equal(t, "alpha\nbeta\n"+readHint+"\n", renderText("", list)) @@ -129,8 +149,8 @@ func TestCutWords(t *testing.T) { {"Hello world again", 11, "Hello..."}, {"Hello world again", 9, "Hello..."}, {"Hello world again", 8, "Hello..."}, - {"Hello world again", 7, "..."}, - {"Unbreakable", 6, "..."}, + {"Hello world again", 7, ""}, + {"Unbreakable", 6, ""}, } for _, tt := range tests { assert.Equal(t, tt.want, cutWords(tt.desc, tt.width), "cutWords(%q, %d)", tt.desc, tt.width) @@ -151,6 +171,14 @@ func TestVisibleSkillsHidesExperimentalKeepsOrder(t *testing.T) { assert.Equal(t, []string{"alpha", "preview", "zeta"}, names(withExperimental)) } +func TestRunListHintsAtExperimentalWhenAllHidden(t *testing.T) { + catalog := &libskills.Catalog{Skills: []libskills.Skill{{Name: "preview", Experimental: true}}} + + cmd, stdout, _ := listTestCmd(t, flags.OutputText) + require.NoError(t, runList(cmd, listFakeSource{catalog}, false)) + assert.Equal(t, "No skills found.\n"+experimentalHint+"\n", stdout.String()) +} + func TestRunListStaleCatalogPrintsProvenanceOnStderr(t *testing.T) { catalog := &libskills.Catalog{ Label: "cached", @@ -166,6 +194,12 @@ func TestRunListStaleCatalogPrintsProvenanceOnStderr(t *testing.T) { assert.NotContains(t, stdout.String(), "Skills come from") } +func TestProvenanceLineOmitsUnknownFetchTime(t *testing.T) { + catalog := &libskills.Catalog{Label: "bundled", Version: "1.2.3", Stale: true} + assert.Equal(t, "Skills come from bundled (release 1.2.3). The source could not be refreshed, so the list may be out of date.", + provenanceLine(catalog)) +} + func names(list []libskills.Skill) []string { var out []string for _, s := range list { From ca310edf7889b558154e0f76edeaf25951c12375 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 16:25:21 +0000 Subject: [PATCH 20/25] Pick the widest skills list width that fits the budget The text length is not monotonic in width: a wider width can drop the search hint, so a binary search could settle on a narrower width than one that fits. Try each width from the widest down instead, and add a test whose widths 35 to 37 are over the budget and 38 fits. Co-authored-by: Isaac --- cmd/skills/list.go | 22 ++++++++++------------ cmd/skills/list_test.go | 23 +++++++++++++++++++++++ 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/cmd/skills/list.go b/cmd/skills/list.go index 54017c1a6e5..d448f79e9ee 100644 --- a/cmd/skills/list.go +++ b/cmd/skills/list.go @@ -101,21 +101,19 @@ func renderText(rules string, list []libskills.Skill) string { for _, s := range list { maxLen = max(maxLen, len(oneLine(s.Description))) } - if full := layoutText(rules, list, maxLen); len(full) <= textBudget { - return full + // The length is not monotonic in width: a wider width can drop the search + // hint once the last dropped description gets its first word, so a binary + // search could settle on a narrower width than a wider one that fits. Try + // each width from the widest down and keep the first that fits. No width + // above textBudget can fit differently from textBudget itself. + for w := min(maxLen, textBudget); w > 0; w-- { + if out := layoutText(rules, list, w); len(out) <= textBudget { + return out + } } // Width 0 leaves every description out, so it is the answer when the names // alone do not fit. - lo, hi := 0, maxLen - for lo < hi { - mid := (lo + hi + 1) / 2 - if len(layoutText(rules, list, mid)) <= textBudget { - lo = mid - } else { - hi = mid - 1 - } - } - return layoutText(rules, list, lo) + return layoutText(rules, list, 0) } // layoutText lays out the text output with descriptions cut to width. A width diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index 83177f07817..fea8e2bc75f 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -129,6 +129,29 @@ func TestRenderTextOneUnbreakableDescriptionDropsOnlyItself(t *testing.T) { assert.Contains(t, out, "databricks skills search ") } +// The search hint goes away once the last dropped description gets its first +// word, so a narrower width can be the one that fits. Widths 35 to 37 are over +// the budget here, and 38 fits with every description shown. +func TestRenderTextKeepsWidestFittingWidth(t *testing.T) { + var list []libskills.Skill + for i := range 84 { + list = append(list, libskills.Skill{ + Name: fmt.Sprintf("skill-%02d", i), + Description: "Deploys the workspace resources, then reports every step taken and any error found.", + }) + } + list = append(list, libskills.Skill{ + Name: "odd", + Description: strings.Repeat("x", 35) + " then more words follow here for the odd skill to show.", + }) + + out := renderText("", list) + + assert.LessOrEqual(t, len(out), textBudget) + assert.Contains(t, out, "odd: "+strings.Repeat("x", 35)+"...\n") + assert.NotContains(t, out, "databricks skills search") +} + func TestRenderTextNoSearchHintWithoutDescriptions(t *testing.T) { list := []libskills.Skill{{Name: "alpha"}, {Name: "beta"}} assert.Equal(t, "alpha\nbeta\n"+readHint+"\n", renderText("", list)) From 047b7e2dce2f22eae0eeb168aa2367172f0ca37e Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 17:09:26 +0000 Subject: [PATCH 21/25] Check the names-only skills list layout before the width search When the names alone do not fit the budget, no description width can fit either, so return the names-only text without trying each width. The early return only applies when the names do not fit even with the search hint, since a wider width can leave that hint out. Change the widest-width test data so that a binary search settles on a narrower width whose output differs. The old search passed this test by landing on a width whose output matched the widest fitting one. Co-authored-by: Isaac --- cmd/skills/list.go | 17 ++++++++++------- cmd/skills/list_test.go | 6 +++--- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/cmd/skills/list.go b/cmd/skills/list.go index d448f79e9ee..8e3800b42c1 100644 --- a/cmd/skills/list.go +++ b/cmd/skills/list.go @@ -97,23 +97,26 @@ func renderText(rules string, list []libskills.Skill) string { if len(list) == 0 { return withRules(rules) + "No skills found.\n" } + // A description only makes its line longer, and the search hint is the one + // line a wider width can leave out. So when the names do not fit even with + // the hint, no width does, and the names-only text is the answer. + names := layoutText(rules, list, 0) + if len(names)-len(searchHint)-1 > textBudget { + return names + } maxLen := 0 for _, s := range list { maxLen = max(maxLen, len(oneLine(s.Description))) } // The length is not monotonic in width: a wider width can drop the search - // hint once the last dropped description gets its first word, so a binary - // search could settle on a narrower width than a wider one that fits. Try - // each width from the widest down and keep the first that fits. No width - // above textBudget can fit differently from textBudget itself. + // hint, so a binary search could settle on a narrower width than one that + // fits. Try each width from the widest down and keep the first that fits. for w := min(maxLen, textBudget); w > 0; w-- { if out := layoutText(rules, list, w); len(out) <= textBudget { return out } } - // Width 0 leaves every description out, so it is the answer when the names - // alone do not fit. - return layoutText(rules, list, 0) + return names } // layoutText lays out the text output with descriptions cut to width. A width diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index fea8e2bc75f..4434a931218 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -130,8 +130,8 @@ func TestRenderTextOneUnbreakableDescriptionDropsOnlyItself(t *testing.T) { } // The search hint goes away once the last dropped description gets its first -// word, so a narrower width can be the one that fits. Widths 35 to 37 are over -// the budget here, and 38 fits with every description shown. +// word. Widths 35 to 37 are over the budget here, 39 is the widest that fits, and +// a binary search settles on 34, which fits only with the hint. func TestRenderTextKeepsWidestFittingWidth(t *testing.T) { var list []libskills.Skill for i := range 84 { @@ -142,7 +142,7 @@ func TestRenderTextKeepsWidestFittingWidth(t *testing.T) { } list = append(list, libskills.Skill{ Name: "odd", - Description: strings.Repeat("x", 35) + " then more words follow here for the odd skill to show.", + Description: strings.Repeat("x", 35) + " more.", }) out := renderText("", list) From 5dd7276a1a2377c636b82cd0d390b06a1f2670e4 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 18:03:21 +0000 Subject: [PATCH 22/25] Bound the skills list width search renderText tried every width from the widest down to 1 until one fit. Each try lays out the whole list, and every layout re-joined each description, so a long catalog spent seconds on widths that were never the answer. Search the widths with binary searches instead. The layout length is not monotonic in the width: once every description is cut the search hint goes away. Below the first width that cuts every description the hint is always there, and from that width on it is never there, so the length only grows within each part. Search the upper part first, then the lower. The result is the same width the full scan picked. Descriptions are joined into one line once per call rather than on every layout. A 400-skill catalog with long descriptions now renders in a few milliseconds. A randomized test checks the output against the full scan. Co-authored-by: Isaac --- cmd/skills/list.go | 65 +++++++++++++++++++++++++----- cmd/skills/list_test.go | 89 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+), 11 deletions(-) diff --git a/cmd/skills/list.go b/cmd/skills/list.go index 8e3800b42c1..af41bb3875a 100644 --- a/cmd/skills/list.go +++ b/cmd/skills/list.go @@ -4,6 +4,7 @@ import ( "fmt" "io" "path/filepath" + "sort" "strings" "time" @@ -97,6 +98,9 @@ func renderText(rules string, list []libskills.Skill) string { if len(list) == 0 { return withRules(rules) + "No skills found.\n" } + // Every width lays the list out again, so each description is joined into + // one line once, here. + list = oneLineSkills(list) // A description only makes its line longer, and the search hint is the one // line a wider width can leave out. So when the names do not fit even with // the hint, no width does, and the names-only text is the answer. @@ -106,29 +110,58 @@ func renderText(rules string, list []libskills.Skill) string { } maxLen := 0 for _, s := range list { - maxLen = max(maxLen, len(oneLine(s.Description))) - } - // The length is not monotonic in width: a wider width can drop the search - // hint, so a binary search could settle on a narrower width than one that - // fits. Try each width from the widest down and keep the first that fits. - for w := min(maxLen, textBudget); w > 0; w-- { - if out := layoutText(rules, list, w); len(out) <= textBudget { - return out - } + maxLen = max(maxLen, len(s.Description)) + } + // No width above maxLen cuts a description, so the widest width to try is + // the smaller of maxLen and the budget. + top := min(maxLen, textBudget) + fits := func(w int) bool { return len(layoutText(rules, list, w)) <= textBudget } + // The length is not monotonic in width: once every description is cut, the + // search hint goes away, so a wider width can be shorter. Below the first + // width that cuts every description the hint is always there, and from that + // width on it never is, so the length only grows within each part. The + // widest fitting width is searched in the upper part first, then the lower. + complete := 1 + sort.Search(top, func(i int) bool { return !dropsAny(list, i+1) }) + if w := widestFitIn(complete, top, fits); w > 0 { + return layoutText(rules, list, w) + } + if w := widestFitIn(1, min(complete-1, top), fits); w > 0 { + return layoutText(rules, list, w) } return names } +// widestFitIn returns the widest width in [lo, hi] that fits, or 0 when lo does +// not fit. Within [lo, hi] fits must hold up to some width and fail above it. +func widestFitIn(lo, hi int, fits func(int) bool) int { + if hi < lo || !fits(lo) { + return 0 + } + first := sort.Search(hi-lo+1, func(i int) bool { return !fits(lo + i) }) + return lo + first - 1 +} + +// dropsAny reports whether layoutText at width leaves some description out. +// It goes false once the width cuts every description, and stays false above it. +func dropsAny(list []libskills.Skill, width int) bool { + for _, s := range list { + if desc := s.Description; desc != "" && cutWords(desc, width) == "" { + return true + } + } + return false +} + // layoutText lays out the text output with descriptions cut to width. A width // of 0 leaves every description out. A skill is listed by its name alone when // its description is left out or has no word boundary within width, so one -// long description does not drop the others. +// long description does not drop the others. Descriptions must be one line. func layoutText(rules string, list []libskills.Skill, width int) string { var b strings.Builder b.WriteString(withRules(rules)) dropped := false for _, s := range list { - desc := oneLine(s.Description) + desc := s.Description cut := "" if width > 0 { cut = cutWords(desc, width) @@ -147,6 +180,16 @@ func layoutText(rules string, list []libskills.Skill, width int) string { return b.String() } +// oneLineSkills returns list with each description joined into one line. +func oneLineSkills(list []libskills.Skill) []libskills.Skill { + out := make([]libskills.Skill, len(list)) + for i, s := range list { + s.Description = oneLine(s.Description) + out[i] = s + } + return out +} + // oneLine joins the words of s with single spaces, so a description takes // exactly one line of output. func oneLine(s string) string { diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index 4434a931218..039252a68c8 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "fmt" + "math/rand/v2" "strings" "testing" "time" @@ -152,6 +153,94 @@ func TestRenderTextKeepsWidestFittingWidth(t *testing.T) { assert.NotContains(t, out, "databricks skills search") } +// renderTextScan is renderText before the width search was bounded: it tries +// every width from the widest down and keeps the first that fits. +func renderTextScan(rules string, list []libskills.Skill) string { + if len(list) == 0 { + return withRules(rules) + "No skills found.\n" + } + list = oneLineSkills(list) + names := layoutText(rules, list, 0) + if len(names)-len(searchHint)-1 > textBudget { + return names + } + maxLen := 0 + for _, s := range list { + maxLen = max(maxLen, len(s.Description)) + } + for w := min(maxLen, textBudget); w > 0; w-- { + if out := layoutText(rules, list, w); len(out) <= textBudget { + return out + } + } + return names +} + +// randomCatalog returns a catalog whose sizes, names, descriptions and rules +// vary with the random source, so the width search meets every case. +func randomCatalog(r *rand.Rand) (string, []libskills.Skill) { + words := []string{"a", "deploy", "the", "workspace", "x", "notebook-run", "describes", "it.", "averyveryverylongwordthatkeepsgoing", " "} + var rules string + if r.IntN(2) == 0 { + rules = strings.Repeat("Pick the skill whose description matches. ", 1+r.IntN(3)) + } + // Some catalogs have names long enough that the names alone exceed the budget. + nameLen := 70 + if r.IntN(6) == 0 { + nameLen = 200 + } + var list []libskills.Skill + for i := range r.IntN(60) { + var desc []string + for range r.IntN(40) { + desc = append(desc, words[r.IntN(len(words))]) + } + sep := " " + if r.IntN(10) == 0 { + sep = "\n" + } + text := strings.Join(desc, sep) + if r.IntN(8) == 0 { + // An unbreakable description has no word boundary to cut at. + text = strings.Repeat("x", r.IntN(300)) + } + list = append(list, libskills.Skill{ + Name: fmt.Sprintf("skill-%d-%s", i, strings.Repeat("n", r.IntN(nameLen))), + Description: text, + }) + } + return rules, list +} + +func TestRenderTextMatchesWidthScan(t *testing.T) { + for seed := range uint64(300) { + r := rand.New(rand.NewPCG(seed, 1)) + rules, list := randomCatalog(r) + want := renderTextScan(rules, list) + got := renderText(rules, list) + if !assert.Equal(t, want, got, "seed %d", seed) { + return + } + } +} + +func TestRenderTextFourHundredLongDescriptionsIsFast(t *testing.T) { + var list []libskills.Skill + for i := range 400 { + desc := strings.Repeat(fmt.Sprintf("word%d describes the skill in detail. ", i), 40) + list = append(list, libskills.Skill{Name: fmt.Sprintf("s%03d", i), Description: desc}) + } + var out string + fastest := time.Hour + for range 3 { + start := time.Now() + out = renderText("Pick the skill whose description matches the task.", list) + fastest = min(fastest, time.Since(start)) + } + assert.LessOrEqual(t, len(out), textBudget) + assert.Less(t, fastest, 50*time.Millisecond) +} + func TestRenderTextNoSearchHintWithoutDescriptions(t *testing.T) { list := []libskills.Skill{{Name: "alpha"}, {Name: "beta"}} assert.Equal(t, "alpha\nbeta\n"+readHint+"\n", renderText("", list)) From fe1d82be52910526ccae029eb57a5b77000472b6 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Fri, 27 Nov 2026 19:13:26 +0000 Subject: [PATCH 23/25] Measure the 400-skill width search in a benchmark The timing assertion measured wall-clock time on the test runner, so it could fail under -race or on a loaded machine while the search was still bounded. Keep the length check as a test and move the timing into BenchmarkRenderTextFourHundredLongDescriptions, which reports time per op. Co-authored-by: Isaac --- cmd/skills/list_test.go | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index 039252a68c8..e014cbff48d 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -224,21 +224,33 @@ func TestRenderTextMatchesWidthScan(t *testing.T) { } } -func TestRenderTextFourHundredLongDescriptionsIsFast(t *testing.T) { +// fourHundredLongSkills returns 400 skills whose descriptions are each far +// longer than the text budget. +func fourHundredLongSkills() []libskills.Skill { var list []libskills.Skill for i := range 400 { desc := strings.Repeat(fmt.Sprintf("word%d describes the skill in detail. ", i), 40) list = append(list, libskills.Skill{Name: fmt.Sprintf("s%03d", i), Description: desc}) } - var out string - fastest := time.Hour - for range 3 { - start := time.Now() - out = renderText("Pick the skill whose description matches the task.", list) - fastest = min(fastest, time.Since(start)) - } + return list +} + +func TestRenderTextFourHundredLongDescriptionsFitsBudget(t *testing.T) { + out := renderText("Pick the skill whose description matches the task.", fourHundredLongSkills()) assert.LessOrEqual(t, len(out), textBudget) - assert.Less(t, fastest, 50*time.Millisecond) + assert.Contains(t, out, "s399") +} + +// BenchmarkRenderTextFourHundredLongDescriptions measures the width search on +// a 400-skill catalog with long descriptions. The time per op is the figure to +// compare against the 50 ms the search must stay under. +func BenchmarkRenderTextFourHundredLongDescriptions(b *testing.B) { + list := fourHundredLongSkills() + const rules = "Pick the skill whose description matches the task." + b.ReportAllocs() + for b.Loop() { + renderText(rules, list) + } } func TestRenderTextNoSearchHintWithoutDescriptions(t *testing.T) { From 607d861e5912a68de06364f51f57bcdfb8f8410a Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Mon, 30 Nov 2026 11:06:43 +0000 Subject: [PATCH 24/25] Tighten width search comments and test Co-authored-by: Isaac --- cmd/skills/list.go | 13 ++++++++----- cmd/skills/list_test.go | 4 +++- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/cmd/skills/list.go b/cmd/skills/list.go index af41bb3875a..9d3c7102f4b 100644 --- a/cmd/skills/list.go +++ b/cmd/skills/list.go @@ -116,16 +116,16 @@ func renderText(rules string, list []libskills.Skill) string { // the smaller of maxLen and the budget. top := min(maxLen, textBudget) fits := func(w int) bool { return len(layoutText(rules, list, w)) <= textBudget } - // The length is not monotonic in width: once every description is cut, the + // The length is not monotonic in width: once no description is left out, the // search hint goes away, so a wider width can be shorter. Below the first - // width that cuts every description the hint is always there, and from that - // width on it never is, so the length only grows within each part. The + // width at which no description is left out the hint is always there, and from + // that width on it never is, so the length only grows within each part. The // widest fitting width is searched in the upper part first, then the lower. complete := 1 + sort.Search(top, func(i int) bool { return !dropsAny(list, i+1) }) if w := widestFitIn(complete, top, fits); w > 0 { return layoutText(rules, list, w) } - if w := widestFitIn(1, min(complete-1, top), fits); w > 0 { + if w := widestFitIn(1, complete-1, fits); w > 0 { return layoutText(rules, list, w) } return names @@ -142,7 +142,8 @@ func widestFitIn(lo, hi int, fits func(int) bool) int { } // dropsAny reports whether layoutText at width leaves some description out. -// It goes false once the width cuts every description, and stays false above it. +// It goes false once no description is left out, and stays false above it. It +// must match the dropped rule in layoutText. func dropsAny(list []libskills.Skill, width int) bool { for _, s := range list { if desc := s.Description; desc != "" && cutWords(desc, width) == "" { @@ -156,6 +157,8 @@ func dropsAny(list []libskills.Skill, width int) bool { // of 0 leaves every description out. A skill is listed by its name alone when // its description is left out or has no word boundary within width, so one // long description does not drop the others. Descriptions must be one line. +// The search hint must stay the only line a wider width can leave out: the +// width search in renderText relies on it, together with dropsAny. func layoutText(rules string, list []libskills.Skill, width int) string { var b strings.Builder b.WriteString(withRules(rules)) diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index e014cbff48d..95c734d68ea 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -239,11 +239,13 @@ func TestRenderTextFourHundredLongDescriptionsFitsBudget(t *testing.T) { out := renderText("Pick the skill whose description matches the task.", fourHundredLongSkills()) assert.LessOrEqual(t, len(out), textBudget) assert.Contains(t, out, "s399") + // Names alone would also fit, so check that descriptions are kept. + assert.Contains(t, out, "s000: word0") } // BenchmarkRenderTextFourHundredLongDescriptions measures the width search on // a 400-skill catalog with long descriptions. The time per op is the figure to -// compare against the 50 ms the search must stay under. +// watch; the full width scan takes seconds on the same catalog. func BenchmarkRenderTextFourHundredLongDescriptions(b *testing.B) { list := fourHundredLongSkills() const rules = "Pick the skill whose description matches the task." From 0416fe8140dcb2bbcab6bfb437fc3619f7c07925 Mon Sep 17 00:00:00 2001 From: "simon.faltum" Date: Mon, 30 Nov 2026 12:13:10 +0000 Subject: [PATCH 25/25] skills list: describe renderTextScan as a reference for the width search Co-authored-by: Isaac --- cmd/skills/list_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cmd/skills/list_test.go b/cmd/skills/list_test.go index 95c734d68ea..ae0c4d906e1 100644 --- a/cmd/skills/list_test.go +++ b/cmd/skills/list_test.go @@ -153,8 +153,9 @@ func TestRenderTextKeepsWidestFittingWidth(t *testing.T) { assert.NotContains(t, out, "databricks skills search") } -// renderTextScan is renderText before the width search was bounded: it tries -// every width from the widest down and keeps the first that fits. +// renderTextScan is a brute-force reference for the width search: it tries +// every width from the widest down and keeps the first that fits. It shares +// oneLineSkills and layoutText with renderText, so it checks the search only. func renderTextScan(rules string, list []libskills.Skill) string { if len(list) == 0 { return withRules(rules) + "No skills found.\n"