diff --git a/.agents/skills/bump-cli-compat/SKILL.md b/.agents/skills/bump-cli-compat/SKILL.md index 2f626650a71..c494ff305f0 100644 --- a/.agents/skills/bump-cli-compat/SKILL.md +++ b/.agents/skills/bump-cli-compat/SKILL.md @@ -64,7 +64,7 @@ If any tag doesn't exist, report the error and stop. ### Step 3: Read current manifest -Read `internal/build/cli-compat.json` and `AgentSkillsFallbackVersion` in `internal/build/clicompat.go`. Note the current versions and the list of versioned entries. The newest CLI range uses `"skills": "latest"`; the compiled constant supplies the tested fallback. Keep older released ranges pinned. Routine skills releases need no manifest bump. CLIs before `1.6.0` reject `"latest"` and use a valid cached or embedded manifest without returning a parse error; losing remote AppKit and skills compatibility updates for these CLIs is accepted. +Read `internal/build/cli-compat.json`. Note the current versions and the list of versioned entries. The newest CLI range sets `"use_latest": true` next to a concrete `skills` pin: the range installs the latest skills release, and the pin is the fallback when the lookup fails and what CLIs from before `use_latest` install. Keep older released ranges pinned. Routine skills releases need no manifest bump. Never write `"skills": "latest"`: CLIs before `1.6.0` reject the whole manifest when any entry uses it. See `internal/build/README.md`. ### Step 4: Determine update type @@ -81,17 +81,17 @@ Ask the user: ### Step 4a: No breaking changes (update in-place) -Update the **highest versioned entry** to the new `appkit` version, keeping `"skills": "latest"`. Update `AgentSkillsFallbackVersion` in `internal/build/clicompat.go` to the tested skills version. Do NOT add new versioned keys. The manifest is range-based: updating the highest entry automatically covers all CLI versions in that range. +Update the **highest versioned entry** to the new `appkit` version and the tested `skills` version, keeping `"use_latest": true`. Do NOT add new versioned keys. The manifest is range-based: updating the highest entry automatically covers all CLI versions in that range. -Write the updated `internal/build/cli-compat.json` and `internal/build/clicompat.go`. +Write the updated `internal/build/cli-compat.json`. ### Step 4b: Breaking changes (add new entry) Ask the user for the **minimum CLI version** that supports the new features. -Add a new entry keyed to that CLI version with the new `appkit` and `"skills": "latest"`. If the previous highest entry has `"auto_install": true`, copy it to the new entry: it turns on the automatic installation of AI tools for its range, so a new entry without it turns the feature off for every newer CLI. Do the same for `"skills_hints": true`, which turns on skill hints for its range. Update `AgentSkillsFallbackVersion` in `internal/build/clicompat.go` to the tested skills version. If skills compatibility changed, replace `"latest"` in the affected older ranges with the last compatible release. Preserve unrelated AppKit and skills compatibility boundaries. +Add a new entry keyed to that CLI version with the new `appkit`, the tested `skills` version and `"use_latest": true`. If the previous highest entry has `"auto_install": true`, copy it to the new entry: it turns on the automatic installation of AI tools for its range, so a new entry without it turns the feature off for every newer CLI. Do the same for `"skills_hints": true`, which turns on skill hints for its range. If skills compatibility changed, drop `use_latest` from the affected older ranges and pin them to the last compatible release. Preserve unrelated AppKit and skills compatibility boundaries. -Write the updated `internal/build/cli-compat.json` and `internal/build/clicompat.go`. +Write the updated `internal/build/cli-compat.json`. ### Step 5: Validate @@ -107,21 +107,21 @@ If validation fails, show the errors and fix them before proceeding. ```bash # Create a new branch from the current branch (or main) -git checkout -b bump-cli-compat-appkit-{appkit_version}-skills-fallback-{skills_version} +git checkout -b bump-cli-compat-appkit-{appkit_version}-skills-{skills_version} # Stage and commit -git add internal/build/cli-compat.json internal/build/clicompat.go -git commit -s -m "Bump cli-compat to appkit {appkit_version}, skills fallback {skills_version}" +git add internal/build/cli-compat.json +git commit -s -m "Bump cli-compat to appkit {appkit_version}, skills {skills_version}" # Push and create PR git push -u origin HEAD gh pr create \ - --title "Bump cli-compat to appkit {appkit_version}, skills fallback {skills_version}" \ + --title "Bump cli-compat to appkit {appkit_version}, skills {skills_version}" \ --body "$(cat <<'EOF' ## Summary Bump `cli-compat.json` to use: - AppKit `{appkit_version}` -- Agent Skills track latest, with compiled fallback `{skills_version}` +- Agent Skills track latest, falling back to `{skills_version}` ## Checklist - [ ] Evals passed with no regressions diff --git a/.nextchanges/cli/aitools-skills-latest-release.md b/.nextchanges/cli/aitools-skills-latest-release.md new file mode 100644 index 00000000000..6c34b19d73b --- /dev/null +++ b/.nextchanges/cli/aitools-skills-latest-release.md @@ -0,0 +1 @@ +* `databricks aitools` commands no longer fail when the latest skills release cannot be looked up: they warn and use the newest release they know, and never downgrade installed skills. The lookup now reads the version file the skills repository publishes on the host that serves the skill files, instead of the rate-limited GitHub API, so `DATABRICKS_CLI_GITHUB_API_URL` no longer affects it and a `DATABRICKS_SKILLS_BASE_URL` mirror must serve `main/metaplugin/version.meta.json` for the lookup to succeed. A compatibility manifest entry can track the latest release with `"use_latest": true`, which older CLI versions ignore. ([#8202](https://github.com/databricks/cli/pull/8202)) diff --git a/acceptance/cmd/aitools/auto-install/script.prepare b/acceptance/cmd/aitools/auto-install/script.prepare index 82351999e10..cf0835f3206 100644 --- a/acceptance/cmd/aitools/auto-install/script.prepare +++ b/acceptance/cmd/aitools/auto-install/script.prepare @@ -52,11 +52,14 @@ use_home() { } # gate true|false [SKILLS] writes a compatibility manifest into the CLI cache -# with that auto_install flag and skills version SKILLS (default: latest). A -# fresh cache file replaces the remote manifest. +# with that auto_install flag, pinned to the skills version SKILLS or, without +# one, tracking the latest release. A fresh cache file replaces the remote +# manifest. gate() { "$mkdir_bin" -p "$DATABRICKS_CACHE_DIR" - echo "{\"0.0.0\": {\"appkit\": \"0.84.0\", \"skills\": \"${2:-latest}\", \"auto_install\": $1}}" > "$DATABRICKS_CACHE_DIR/compat-manifest.json" + local skills="\"skills\": \"0.0.1\", \"use_latest\": true" + if [ -n "${2:-}" ]; then skills="\"skills\": \"$2\""; fi + echo "{\"0.0.0\": {\"appkit\": \"0.84.0\", $skills, \"auto_install\": $1}}" > "$DATABRICKS_CACHE_DIR/compat-manifest.json" } # cursor_skills lists the skills installed for Cursor. diff --git a/acceptance/cmd/aitools/auto-install/test.toml b/acceptance/cmd/aitools/auto-install/test.toml index ac8b3d78560..df53cde7e78 100644 --- a/acceptance/cmd/aitools/auto-install/test.toml +++ b/acceptance/cmd/aitools/auto-install/test.toml @@ -1,8 +1,7 @@ # Automatic installation of Databricks AI tools on the first run of a new CLI -# version. The mock server replaces raw.githubusercontent.com (skills manifest -# and files) and the GitHub API (latest skills release). +# version. The mock server replaces raw.githubusercontent.com: the skills +# manifest and files, and the version file of the latest skills release. Env.DATABRICKS_SKILLS_BASE_URL = "$DATABRICKS_HOST" -Env.DATABRICKS_CLI_GITHUB_API_URL = "$DATABRICKS_HOST" Env.DATABRICKS_SKILLS_REF = "test-ref" RecordRequests = true # Pin it so an opt-out exported in the developer's shell does not change the output. diff --git a/acceptance/cmd/aitools/auto-install/upgrade/output.txt b/acceptance/cmd/aitools/auto-install/upgrade/output.txt index 97512d43cf7..89522e2f899 100644 --- a/acceptance/cmd/aitools/auto-install/upgrade/output.txt +++ b/acceptance/cmd/aitools/auto-install/upgrade/output.txt @@ -25,7 +25,7 @@ databricks-kept === upgrade to 1.31.0 with release 0.4.0: updates like aitools update, keeping the edited skills ->>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_CLI_GITHUB_API_URL=[DATABRICKS_URL]/newer [CLI] jobs list +>>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_SKILLS_BASE_URL=[DATABRICKS_URL]/newer [CLI] jobs list Updated Databricks AI tools for Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall >>> print_telemetry @@ -56,7 +56,7 @@ my notes === upgrade to 1.32.0 while the latest release is 0.2.0: no downgrade, nothing printed, not retried ->>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.32.0 DATABRICKS_CLI_GITHUB_API_URL=[DATABRICKS_URL]/older [CLI] jobs list +>>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.32.0 DATABRICKS_SKILLS_BASE_URL=[DATABRICKS_URL]/older [CLI] jobs list >>> print_telemetry {"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"KEPT","holdout_arm":"TREATMENT","interactive":false}} @@ -84,7 +84,7 @@ kept 2.0.0 "id": "treatment-machine" } ->>> DATABRICKS_SKILLS_REF=v0.4.0 [CLI] aitools install --skills-only --scope=global --agents=cursor +>>> DATABRICKS_SKILLS_REF=v0.4.0 DATABRICKS_SKILLS_BASE_URL=[DATABRICKS_URL]/newer [CLI] aitools install --skills-only --scope=global --agents=cursor Installing Databricks skills for Cursor... Using skills version 0.4.0 Fetching skills manifest... @@ -92,10 +92,10 @@ Installed 2 skills in [TEST_TMP_DIR]/pinned-home/.databricks/aitools/skills. === upgrade to 1.33.0 pinned to 0.3.0 over an explicit 0.4.0 install: no downgrade, nothing printed, not retried ->>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.33.0 [CLI] jobs list +>>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.33.0 DATABRICKS_SKILLS_BASE_URL=[DATABRICKS_URL]/newer [CLI] jobs list >>> print_telemetry -{"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"KEPT","holdout_arm":"TREATMENT","interactive":false}} +{"command":"jobs_list","exit_code":0,"aitools_auto_install_event":{"outcome":"UP_TO_DATE","holdout_arm":"TREATMENT","interactive":false}} >>> cursor_skills databricks-edited @@ -119,7 +119,7 @@ Installed 3 skills in [TEST_TMP_DIR]/existing-home/.databricks/aitools/skills. === upgrade to 1.31.0 over an installation of a machine whose user never answered: updated, and the installation counts as the consent ->>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_CLI_GITHUB_API_URL=[DATABRICKS_URL]/newer [CLI] jobs list +>>> DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_SKILLS_BASE_URL=[DATABRICKS_URL]/newer [CLI] jobs list Updated Databricks AI tools for Cursor. Turn off: databricks aitools auto-install disable. Remove: databricks aitools uninstall >>> print_telemetry diff --git a/acceptance/cmd/aitools/auto-install/upgrade/script b/acceptance/cmd/aitools/auto-install/upgrade/script index 2f4a7bf00be..8e6a0b4cdb5 100644 --- a/acceptance/cmd/aitools/auto-install/upgrade/script +++ b/acceptance/cmd/aitools/auto-install/upgrade/script @@ -19,7 +19,7 @@ echo "my notes" >> "$skills_dir/databricks-dropped/SKILL.md" echo "my notes" >> "$skills_dir/databricks-edited/SKILL.md" title "upgrade to 1.31.0 with release 0.4.0: updates like aitools update, keeping the edited skills" -trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_CLI_GITHUB_API_URL=$DATABRICKS_HOST/newer $CLI jobs list +trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_SKILLS_BASE_URL=$DATABRICKS_HOST/newer $CLI jobs list trace print_telemetry trace cursor_skills trace skill_file databricks-kept @@ -28,7 +28,7 @@ trace skill_file databricks-edited trace auto_install_state title "upgrade to 1.32.0 while the latest release is 0.2.0: no downgrade, nothing printed, not retried" -trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.32.0 DATABRICKS_CLI_GITHUB_API_URL=$DATABRICKS_HOST/older $CLI jobs list +trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.32.0 DATABRICKS_SKILLS_BASE_URL=$DATABRICKS_HOST/older $CLI jobs list trace print_telemetry trace skill_file databricks-kept trace auto_install_state @@ -42,12 +42,13 @@ trace auto_install_state # manifest pins this CLI to the older 0.3.0, as it pins released CLIs. use_home pinned-home skills_dir="${USERPROFILE:-$HOME}/.databricks/aitools/skills" -trace DATABRICKS_SKILLS_REF=v0.4.0 $CLI aitools install --skills-only --scope=global --agents=cursor +trace DATABRICKS_SKILLS_REF=v0.4.0 DATABRICKS_SKILLS_BASE_URL=$DATABRICKS_HOST/newer $CLI aitools install --skills-only --scope=global --agents=cursor print_telemetry > /dev/null gate true 0.3.0 title "upgrade to 1.33.0 pinned to 0.3.0 over an explicit 0.4.0 install: no downgrade, nothing printed, not retried" -trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.33.0 $CLI jobs list +# The host that served the installed 0.4.0 still serves it. +trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.33.0 DATABRICKS_SKILLS_BASE_URL=$DATABRICKS_HOST/newer $CLI jobs list trace print_telemetry trace cursor_skills trace skill_file databricks-kept @@ -62,7 +63,7 @@ echo '{"id": "treatment-machine", "last_version": "1.30.0"}' > "${USERPROFILE:-$ gate true title "upgrade to 1.31.0 over an installation of a machine whose user never answered: updated, and the installation counts as the consent" -trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_CLI_GITHUB_API_URL=$DATABRICKS_HOST/newer $CLI jobs list +trace DATABRICKS_AITOOLS_AUTO_INSTALL_CLI_VERSION=1.31.0 DATABRICKS_SKILLS_BASE_URL=$DATABRICKS_HOST/newer $CLI jobs list trace print_telemetry trace cursor_skills trace auto_install_state diff --git a/acceptance/cmd/aitools/auto-install/upgrade/test.toml b/acceptance/cmd/aitools/auto-install/upgrade/test.toml index b266d3f1f19..9bf4f78ecfc 100644 --- a/acceptance/cmd/aitools/auto-install/upgrade/test.toml +++ b/acceptance/cmd/aitools/auto-install/upgrade/test.toml @@ -1,19 +1,20 @@ Ignore = ["pinned-home", "existing-home"] # Skills releases: the latest release is v0.3.0, under /newer it is v0.4.0 and -# under /older it is v0.2.0 (DATABRICKS_CLI_GITHUB_API_URL picks one). +# under /older it is v0.2.0 (DATABRICKS_SKILLS_BASE_URL picks one; the manifest +# and files of a release are served under the same prefix as its version file). [[Server]] -Pattern = "GET /repos/databricks/databricks-agent-skills/releases/latest" -Response.Body = '{"tag_name": "v0.3.0"}' +Pattern = "GET /main/metaplugin/version.meta.json" +Response.Body = '{"current_version": "0.3.0", "next_version": "0.3.1"}' [[Server]] -Pattern = "GET /newer/repos/databricks/databricks-agent-skills/releases/latest" -Response.Body = '{"tag_name": "v0.4.0"}' +Pattern = "GET /newer/main/metaplugin/version.meta.json" +Response.Body = '{"current_version": "0.4.0", "next_version": "0.4.1"}' [[Server]] -Pattern = "GET /older/repos/databricks/databricks-agent-skills/releases/latest" -Response.Body = '{"tag_name": "v0.2.0"}' +Pattern = "GET /older/main/metaplugin/version.meta.json" +Response.Body = '{"current_version": "0.2.0", "next_version": "0.2.1"}' [[Server]] Pattern = "GET /v0.3.0/manifest.json" @@ -42,7 +43,7 @@ Pattern = "GET /v0.3.0/skills/databricks-edited/SKILL.md" Response.Body = "edited 1.0.0\n" [[Server]] -Pattern = "GET /v0.4.0/manifest.json" +Pattern = "GET /newer/v0.4.0/manifest.json" Response.Body = ''' { "version": "2", @@ -55,15 +56,15 @@ Response.Body = ''' ''' [[Server]] -Pattern = "GET /v0.4.0/skills/databricks-kept/SKILL.md" +Pattern = "GET /newer/v0.4.0/skills/databricks-kept/SKILL.md" Response.Body = "kept 2.0.0\n" [[Server]] -Pattern = "GET /v0.4.0/skills/databricks-edited/SKILL.md" +Pattern = "GET /newer/v0.4.0/skills/databricks-edited/SKILL.md" Response.Body = "edited 2.0.0\n" [[Server]] -Pattern = "GET /v0.2.0/manifest.json" +Pattern = "GET /older/v0.2.0/manifest.json" Response.Body = ''' { "version": "2", diff --git a/acceptance/cmd/aitools/list/latest-lookup-fails/compat-manifest.json b/acceptance/cmd/aitools/list/latest-lookup-fails/compat-manifest.json index eaa0f4668b3..68894446000 100644 --- a/acceptance/cmd/aitools/list/latest-lookup-fails/compat-manifest.json +++ b/acceptance/cmd/aitools/list/latest-lookup-fails/compat-manifest.json @@ -1 +1 @@ -{"1.0.0": {"appkit": "0.84.0", "skills": "latest"}} +{"1.0.0": {"appkit": "0.84.0", "skills": "0.9.0", "use_latest": true}} diff --git a/acceptance/cmd/aitools/list/latest-lookup-fails/output.txt b/acceptance/cmd/aitools/list/latest-lookup-fails/output.txt index 8856e2db261..5d57b86b29d 100644 --- a/acceptance/cmd/aitools/list/latest-lookup-fails/output.txt +++ b/acceptance/cmd/aitools/list/latest-lookup-fails/output.txt @@ -1,11 +1,36 @@ ->>> musterr [CLI] aitools list --output json -Error: resolve latest skills release: HTTP 403 fetching latest skills release +>>> [CLI] aitools list --output json +Warn: Could not resolve the latest skills release (HTTP 403 fetching latest skills release); using 0.9.0 +{ + "release": "0.9.0", + "skills": [ + { + "name": "test-skill", + "latest_version": "1.0.0", + "experimental": false, + "installed": {} + } + ], + "summary": { + "global": { + "installed": 0, + "total": 1 + }, + "project": { + "installed": 0, + "total": 1 + } + } +} -=== The lookup fails, so the manifest is never fetched +=== The lookup fails, so the manifest of the fallback release is fetched >>> print_requests.py --get ^//telemetry-ext ^//.well-known { "method": "GET", - "path": "/repos/databricks/databricks-agent-skills/releases/latest" + "path": "/main/metaplugin/version.meta.json" +} +{ + "method": "GET", + "path": "/v0.9.0/manifest.json" } diff --git a/acceptance/cmd/aitools/list/latest-lookup-fails/script b/acceptance/cmd/aitools/list/latest-lookup-fails/script index f419091ed28..10f95f1a55c 100644 --- a/acceptance/cmd/aitools/list/latest-lookup-fails/script +++ b/acceptance/cmd/aitools/list/latest-lookup-fails/script @@ -2,9 +2,9 @@ sethome home use_compat_manifest -# Known gap: list does not fall back to the embedded skills version, so a -# failed latest-release lookup fails the command. -trace musterr $CLI aitools list --output json +# A failed lookup of the latest release falls back to the release the +# compatibility manifest names, so the command still lists the skills. +trace $CLI aitools list --output json | list_fields -title "The lookup fails, so the manifest is never fetched" +title "The lookup fails, so the manifest of the fallback release is fetched" trace print_requests.py --get '^//telemetry-ext' '^//.well-known' diff --git a/acceptance/cmd/aitools/list/latest-lookup-fails/test.toml b/acceptance/cmd/aitools/list/latest-lookup-fails/test.toml index d17526f92a8..f0233e9b6e0 100644 --- a/acceptance/cmd/aitools/list/latest-lookup-fails/test.toml +++ b/acceptance/cmd/aitools/list/latest-lookup-fails/test.toml @@ -1,5 +1,5 @@ -# The unauthenticated GitHub API answers 403 when the per-IP rate limit is hit. +# The skills host refuses the version file of the latest release. [[Server]] -Pattern = "GET /repos/databricks/databricks-agent-skills/releases/latest" +Pattern = "GET /main/metaplugin/version.meta.json" Response.StatusCode = 403 -Response.Body = '{"message": "API rate limit exceeded"}' +Response.Body = '{"message": "Forbidden"}' diff --git a/acceptance/cmd/aitools/list/latest/compat-manifest.json b/acceptance/cmd/aitools/list/latest/compat-manifest.json index eaa0f4668b3..d014a2feb97 100644 --- a/acceptance/cmd/aitools/list/latest/compat-manifest.json +++ b/acceptance/cmd/aitools/list/latest/compat-manifest.json @@ -1 +1 @@ -{"1.0.0": {"appkit": "0.84.0", "skills": "latest"}} +{"1.0.0": {"appkit": "0.84.0", "skills": "0.2.30", "use_latest": true}} diff --git a/acceptance/cmd/aitools/list/latest/output.txt b/acceptance/cmd/aitools/list/latest/output.txt index b6700496e81..0bce4f57ca9 100644 --- a/acceptance/cmd/aitools/list/latest/output.txt +++ b/acceptance/cmd/aitools/list/latest/output.txt @@ -27,7 +27,11 @@ >>> print_requests.py --get ^//telemetry-ext ^//.well-known { "method": "GET", - "path": "/repos/databricks/databricks-agent-skills/releases/latest" + "path": "/main/metaplugin/version.meta.json" +} +{ + "method": "GET", + "path": "/v0.2.33/manifest.json" } { "method": "GET", diff --git a/acceptance/cmd/aitools/list/latest/test.toml b/acceptance/cmd/aitools/list/latest/test.toml index 4ab7e64bf67..3cf95fb266d 100644 --- a/acceptance/cmd/aitools/list/latest/test.toml +++ b/acceptance/cmd/aitools/list/latest/test.toml @@ -1,3 +1,3 @@ [[Server]] -Pattern = "GET /repos/databricks/databricks-agent-skills/releases/latest" -Response.Body = '{"tag_name": "v0.2.33"}' +Pattern = "GET /main/metaplugin/version.meta.json" +Response.Body = '{"current_version": "0.2.33", "next_version": "0.2.34"}' diff --git a/acceptance/cmd/aitools/list/test.toml b/acceptance/cmd/aitools/list/test.toml index 7e9761d5c88..a8fa7af5201 100644 --- a/acceptance/cmd/aitools/list/test.toml +++ b/acceptance/cmd/aitools/list/test.toml @@ -1,7 +1,6 @@ -# The mock server replaces raw.githubusercontent.com (skills manifest) and -# api.github.com (latest skills release lookup). +# The mock server replaces raw.githubusercontent.com: the skills manifest and +# the version file of the latest skills release. Env.DATABRICKS_SKILLS_BASE_URL = "$DATABRICKS_HOST" -Env.DATABRICKS_CLI_GITHUB_API_URL = "$DATABRICKS_HOST" # Use the skills ref and the compat manifest that each test sets, even if the # shell sets other values. Env.DATABRICKS_SKILLS_REF = "" diff --git a/acceptance/cmd/aitools/list/update-check-lookup-fails/compat-manifest.json b/acceptance/cmd/aitools/list/update-check-lookup-fails/compat-manifest.json new file mode 100644 index 00000000000..68894446000 --- /dev/null +++ b/acceptance/cmd/aitools/list/update-check-lookup-fails/compat-manifest.json @@ -0,0 +1 @@ +{"1.0.0": {"appkit": "0.84.0", "skills": "0.9.0", "use_latest": true}} diff --git a/acceptance/cmd/aitools/list/update-check-lookup-fails/out.test.toml b/acceptance/cmd/aitools/list/update-check-lookup-fails/out.test.toml new file mode 100644 index 00000000000..18b1a88417e --- /dev/null +++ b/acceptance/cmd/aitools/list/update-check-lookup-fails/out.test.toml @@ -0,0 +1 @@ +Cloud = false diff --git a/acceptance/cmd/aitools/list/update-check-lookup-fails/output.txt b/acceptance/cmd/aitools/list/update-check-lookup-fails/output.txt new file mode 100644 index 00000000000..a2ff6f33000 --- /dev/null +++ b/acceptance/cmd/aitools/list/update-check-lookup-fails/output.txt @@ -0,0 +1,13 @@ + +=== A check cannot tell whether a newer release exists, so it checks nothing + +>>> musterr [CLI] aitools update --check --scope=global +Warn: Could not resolve the latest skills release: HTTP 403 fetching latest skills release +Error: nothing was checked: HTTP 403 fetching latest skills release + +=== The version shows no update line + +>>> [CLI] aitools version +Databricks skills and plugins: + Skills (global): v0.9.0 (1 skill) + Last updated: [DATE] diff --git a/acceptance/cmd/aitools/list/update-check-lookup-fails/script b/acceptance/cmd/aitools/list/update-check-lookup-fails/script new file mode 100644 index 00000000000..e2687a9f3b6 --- /dev/null +++ b/acceptance/cmd/aitools/list/update-check-lookup-fails/script @@ -0,0 +1,11 @@ +# Isolate HOME so parallel aitools tests don't race on a shared ~/.databricks. +sethome home +mkdir -p "${USERPROFILE:-$HOME}/.cursor" +use_compat_manifest +DATABRICKS_SKILLS_REF=v0.9.0 $CLI aitools install --skills-only --scope=global --agents=cursor &> LOG.install + +title "A check cannot tell whether a newer release exists, so it checks nothing" +trace musterr $CLI aitools update --check --scope=global + +title "The version shows no update line" +trace $CLI aitools version diff --git a/acceptance/cmd/aitools/list/update-check-lookup-fails/test.toml b/acceptance/cmd/aitools/list/update-check-lookup-fails/test.toml new file mode 100644 index 00000000000..8c24ba4f61c --- /dev/null +++ b/acceptance/cmd/aitools/list/update-check-lookup-fails/test.toml @@ -0,0 +1,16 @@ +# The skills host refuses the version file of the latest release. +[[Server]] +Pattern = "GET /main/metaplugin/version.meta.json" +Response.StatusCode = 403 +Response.Body = '{"message": "Forbidden"}' + +[[Server]] +Pattern = "GET /v0.9.0/skills/test-skill/SKILL.md" +Response.Body = '''--- +name: test-skill +--- +''' + +[[Repls]] +Old = 'Last updated: \d{4}-\d{2}-\d{2}' +New = 'Last updated: [DATE]' diff --git a/acceptance/cmd/aitools/telemetry/test.toml b/acceptance/cmd/aitools/telemetry/test.toml index 085fd7d6d90..10f586781e5 100644 --- a/acceptance/cmd/aitools/telemetry/test.toml +++ b/acceptance/cmd/aitools/telemetry/test.toml @@ -1,7 +1,6 @@ # Telemetry payloads of the aitools commands and of the install hint. # The mock server replaces raw.githubusercontent.com (skills manifest and files). Env.DATABRICKS_SKILLS_BASE_URL = "$DATABRICKS_HOST" -Env.DATABRICKS_CLI_GITHUB_API_URL = "$DATABRICKS_HOST" Env.DATABRICKS_SKILLS_REF = "test-ref" Env.CLAUDE_CONFIG_DIR = "" Env.CODEX_HOME = "" diff --git a/cmd/aitools/funnel_test.go b/cmd/aitools/funnel_test.go index 733908863ad..3ab6f091840 100644 --- a/cmd/aitools/funnel_test.go +++ b/cmd/aitools/funnel_test.go @@ -934,9 +934,10 @@ func TestUpdateFunnelWhenPluginsFail(t *testing.T) { {name: "one of two plugins failed", results: []installer.PluginUpdate{{Agent: "Claude Code", Version: "0.2.7"}, codexFailed}, want: "FINISHED:SUCCESS:"}, {name: "plugin failed, file skills reconciled", skills: map[string]string{"databricks": "0.2.6"}, results: []installer.PluginUpdate{codexFailed}, want: "FINISHED:SUCCESS:"}, {name: "plugin failed, raw skills migrated", results: []installer.PluginUpdate{codexFailed}, migrate: true, want: "FINISHED:SUCCESS:"}, - {name: "skills ref lookup failed", refErr: fmt.Errorf("resolve latest skills release: %w", context.DeadlineExceeded), want: "FINISHED:FAILURE:TIMEOUT"}, + // The plugins still update from the agent's marketplace when the latest release is unknown. + {name: "latest release unknown, plugins updated", results: []installer.PluginUpdate{{Agent: "Claude Code"}}, refErr: context.DeadlineExceeded, want: "FINISHED:SUCCESS:"}, {name: "check, plugins checked", check: true, want: "FINISHED:SUCCESS:"}, - {name: "check, skills ref lookup failed", check: true, refErr: fmt.Errorf("resolve latest skills release: %w", context.DeadlineExceeded), want: "FINISHED:FAILURE:TIMEOUT"}, + {name: "check, latest release unknown, plugins checked", check: true, refErr: context.DeadlineExceeded, want: "FINISHED:SUCCESS:"}, {name: "check, skills manifest fetch failed", skills: map[string]string{"databricks": "0.2.6"}, noPlugins: true, check: true, checkErr: fmt.Errorf("fetch manifest: %w", context.DeadlineExceeded), want: "FINISHED:FAILURE:TIMEOUT"}, {name: "check, skills manifest fetch failed, plugins checked", skills: map[string]string{"databricks": "0.2.6"}, check: true, checkErr: fmt.Errorf("fetch manifest: %w", context.DeadlineExceeded), want: "FINISHED:SUCCESS:"}, } @@ -949,11 +950,12 @@ func TestUpdateFunnelWhenPluginsFail(t *testing.T) { require.NoError(t, installer.SaveState(dir, &installer.InstallState{SchemaVersion: 2, Release: "v0.2.6", Skills: tc.skills})) } resetUpdatePluginSeams(t) - origRef, origUpdateSkills := updateGetSkillsRefFn, updateSkillsFn - t.Cleanup(func() { updateGetSkillsRefFn, updateSkillsFn = origRef, origUpdateSkills }) + origRef, origUpdateSkills := updateResolveReleaseFn, updateSkillsFn + t.Cleanup(func() { updateResolveReleaseFn, updateSkillsFn = origRef, origUpdateSkills }) - updateGetSkillsRefFn = func(context.Context) (string, bool, error) { - return "v0.2.7", true, tc.refErr + // A failed lookup of the latest release resolves the fallback release. + updateResolveReleaseFn = func(context.Context) (installer.Release, error) { + return installer.Release{Ref: "v0.2.7", Pinned: tc.refErr == nil, LookupErr: tc.refErr}, nil } updatePluginsFn = func(context.Context, string, string) ([]installer.PluginUpdate, error) { assert.False(t, tc.check, "--check must not update plugins") diff --git a/cmd/aitools/install.go b/cmd/aitools/install.go index ea43c89606e..54a292fa2f4 100644 --- a/cmd/aitools/install.go +++ b/cmd/aitools/install.go @@ -1094,10 +1094,13 @@ func executePlan(ctx context.Context, src installer.ManifestSource, plan []agent if len(pluginItems) > 0 { // Plugins install from the agent's marketplace, so the skills ref only // labels the recorded version. Record it as unknown when unresolved. - ref, _, err := installer.GetSkillsRef(ctx) - if err != nil { + ref := "" + if rel, err := installer.ResolveRelease(ctx, "", true); err != nil { log.Debugf(ctx, "Recording plugin version as unknown: %v", err) - ref = "" + } else if rel.LookupErr != nil { + log.Debugf(ctx, "Recording plugin version as unknown: %v", rel.LookupErr) + } else { + ref = rel.Ref } records := map[string]installer.PluginRecord{} var failed []string diff --git a/cmd/aitools/install_test.go b/cmd/aitools/install_test.go index f4c7eff22c5..73931ac6cb4 100644 --- a/cmd/aitools/install_test.go +++ b/cmd/aitools/install_test.go @@ -989,7 +989,7 @@ func TestExecutePlanPluginWithUnresolvedSkillsRelease(t *testing.T) { w.WriteHeader(http.StatusForbidden) })) t.Cleanup(srv.Close) - t.Setenv("DATABRICKS_CLI_GITHUB_API_URL", srv.URL) + t.Setenv("DATABRICKS_SKILLS_BASE_URL", srv.URL) installRef, recordRef := "unset", "unset" orig := installPluginForAgentFn diff --git a/cmd/aitools/list.go b/cmd/aitools/list.go index dc4658056b2..957b8ec9a03 100644 --- a/cmd/aitools/list.go +++ b/cmd/aitools/list.go @@ -148,13 +148,14 @@ func defaultListSkills(cmd *cobra.Command, scope string) error { // returns the structured listOutput. scope=="" loads both scopes; "global" // or "project" loads only that scope. func buildListOutput(ctx context.Context, scope string) (listOutput, error) { - ref, explicit, err := installer.GetSkillsRef(ctx) + rel, err := installer.ResolveRelease(ctx, "", true) if err != nil { return listOutput{}, err } + installer.WarnLookupFallback(ctx, rel) src := &installer.GitHubManifestSource{} - manifest, ref, err := installer.FetchSkillsManifestWithFallback(ctx, src, ref, !explicit) + manifest, ref, err := installer.FetchSkillsManifestWithFallback(ctx, src, rel.Ref, !rel.Pinned) if err != nil { return listOutput{}, fmt.Errorf("failed to fetch manifest: %w", err) } diff --git a/cmd/aitools/recovery.go b/cmd/aitools/recovery.go index f6027b248ce..d649af09bd9 100644 --- a/cmd/aitools/recovery.go +++ b/cmd/aitools/recovery.go @@ -213,7 +213,7 @@ func installRecovery(ctx context.Context, inv installInvocation, err error) stri return releaseLookupRecovery(ctx, rerun) case protos.AitoolsErrorCategoryRateLimited: if ferr.Stage == installer.FetchStageRelease { - return releaseHost(ctx) + " rate-limited the lookup of the latest Databricks skills release. " + releaseLookupStep(rerun) + return skillsHost(ctx) + " rate-limited the lookup of the latest Databricks skills release. " + releaseLookupStep(rerun) } return skillsHost(ctx) + " rate-limited the download (HTTP " + strconv.Itoa(ferr.StatusCode) + "). Wait a few minutes and re-run " + rerun + "." case protos.AitoolsErrorCategoryManifestNotFound: @@ -288,7 +288,7 @@ func promptRecovery(inv installInvocation) string { // releaseLookupRecovery is the step for a lookup of the latest skills release // that failed for any reason but a rate limit. func releaseLookupRecovery(ctx context.Context, rerun string) string { - return "Could not look up the latest Databricks skills release on " + releaseHost(ctx) + ". " + releaseLookupStep(rerun) + return "Could not look up the latest Databricks skills release on " + skillsHost(ctx) + ". " + releaseLookupStep(rerun) } // releaseLookupStep is what to do after a failed lookup of the latest skills @@ -297,12 +297,8 @@ func releaseLookupStep(rerun string) string { return "Wait a few minutes and re-run " + rerun + ", or skip the lookup by setting DATABRICKS_SKILLS_REF to a release tag from " + skillsReleasesURL + "." } -// releaseHost is the host the latest skills release is looked up on. -func releaseHost(ctx context.Context) string { - return hostOf(versioncheck.GitHubAPIURL(ctx)) -} - -// skillsHost is the host the skills manifest and files are downloaded from. +// skillsHost is the host the skills manifest and files are downloaded from, +// and the latest skills release is looked up on. func skillsHost(ctx context.Context) string { return hostOf(installer.GetSkillsBaseURL(ctx)) } diff --git a/cmd/aitools/recovery_test.go b/cmd/aitools/recovery_test.go index 21ef56bcc15..871f6a8843b 100644 --- a/cmd/aitools/recovery_test.go +++ b/cmd/aitools/recovery_test.go @@ -38,17 +38,17 @@ func TestInstallRecovery(t *testing.T) { { name: "release lookup rate limited", err: fmt.Errorf("resolve latest skills release: %w", &installer.FetchError{Stage: installer.FetchStageRelease, StatusCode: http.StatusForbidden, RateLimited: true, Err: errors.New("HTTP 403 fetching latest skills release")}), - want: "api.github.com rate-limited the lookup of the latest Databricks skills release. Wait a few minutes and re-run 'databricks aitools install', or skip the lookup by setting DATABRICKS_SKILLS_REF to a release tag from https://github.com/databricks/databricks-agent-skills/releases.", + want: "raw.githubusercontent.com rate-limited the lookup of the latest Databricks skills release. Wait a few minutes and re-run 'databricks aitools install', or skip the lookup by setting DATABRICKS_SKILLS_REF to a release tag from https://github.com/databricks/databricks-agent-skills/releases.", }, { name: "release lookup denied without rate-limit evidence", err: &installer.FetchError{Stage: installer.FetchStageRelease, StatusCode: http.StatusForbidden, Err: errors.New("HTTP 403 fetching latest skills release")}, - want: "Could not look up the latest Databricks skills release on api.github.com. Wait a few minutes and re-run 'databricks aitools install', or skip the lookup by setting DATABRICKS_SKILLS_REF to a release tag from https://github.com/databricks/databricks-agent-skills/releases.", + want: "Could not look up the latest Databricks skills release on raw.githubusercontent.com. Wait a few minutes and re-run 'databricks aitools install', or skip the lookup by setting DATABRICKS_SKILLS_REF to a release tag from https://github.com/databricks/databricks-agent-skills/releases.", }, { name: "release lookup network error", err: &installer.FetchError{Stage: installer.FetchStageRelease, Err: dnsError}, - want: "Could not look up the latest Databricks skills release on api.github.com. Wait a few minutes and re-run 'databricks aitools install', or skip the lookup by setting DATABRICKS_SKILLS_REF to a release tag from https://github.com/databricks/databricks-agent-skills/releases.", + want: "Could not look up the latest Databricks skills release on raw.githubusercontent.com. Wait a few minutes and re-run 'databricks aitools install', or skip the lookup by setting DATABRICKS_SKILLS_REF to a release tag from https://github.com/databricks/databricks-agent-skills/releases.", }, { name: "manifest fetch server error", @@ -217,9 +217,9 @@ func TestFetchRecoveryNamesOverriddenHost(t *testing.T) { } func TestReleaseLookupRecoveryNamesOverriddenHost(t *testing.T) { - t.Setenv("DATABRICKS_CLI_GITHUB_API_URL", "https://ghe.example.test/api/v3") + t.Setenv("DATABRICKS_SKILLS_BASE_URL", "https://mirror.example.test/skills") got := installRecovery(t.Context(), installInvocation{}, &installer.FetchError{Stage: installer.FetchStageRelease, Err: dnsError}) - assert.Contains(t, got, "Could not look up the latest Databricks skills release on ghe.example.test.") + assert.Contains(t, got, "Could not look up the latest Databricks skills release on mirror.example.test.") } func TestPluginFailureText(t *testing.T) { diff --git a/cmd/aitools/telemetry_auth_test.go b/cmd/aitools/telemetry_auth_test.go index 82e54f09ce6..dff6f998df6 100644 --- a/cmd/aitools/telemetry_auth_test.go +++ b/cmd/aitools/telemetry_auth_test.go @@ -377,10 +377,10 @@ func TestUpdateAndUninstallWorkWaitsForTelemetryAuth(t *testing.T) { saveGlobalSkill(t) release := blockTelemetryAuth(t) resetUpdatePluginSeams(t) - origRef, origUpdateSkills := updateGetSkillsRefFn, updateSkillsFn - t.Cleanup(func() { updateGetSkillsRefFn, updateSkillsFn = origRef, origUpdateSkills }) - updateGetSkillsRefFn = func(context.Context) (string, bool, error) { - return "v0.2.6", true, nil + origRef, origUpdateSkills := updateResolveReleaseFn, updateSkillsFn + t.Cleanup(func() { updateResolveReleaseFn, updateSkillsFn = origRef, origUpdateSkills }) + updateResolveReleaseFn = func(context.Context) (installer.Release, error) { + return installer.Release{Ref: "v0.2.6", Pinned: true}, nil } updateSkillsFn = func(context.Context, installer.ManifestSource, []*agents.Agent, installer.UpdateOptions) (*installer.UpdateResult, error) { time.AfterFunc(200*time.Millisecond, release) diff --git a/cmd/aitools/update.go b/cmd/aitools/update.go index d11d071ac1c..8c60ebe32bf 100644 --- a/cmd/aitools/update.go +++ b/cmd/aitools/update.go @@ -23,7 +23,7 @@ var updateSkillsFn = func(ctx context.Context, src installer.ManifestSource, ins } var ( - updateGetSkillsRefFn = installer.GetSkillsRef + updateResolveReleaseFn = resolveLatestRelease updatePluginsFn = installer.UpdateInstalledPlugins updateInstallPluginForAgentFn = installer.InstallPluginForAgent updateRecordPluginInstallsFn = installer.RecordPluginInstalls @@ -41,6 +41,12 @@ type pluginMigrationResult struct { record installer.PluginRecord } +// resolveLatestRelease resolves the skills release that labels the plugin +// records, with the fallback release when the latest one cannot be resolved. +func resolveLatestRelease(ctx context.Context) (installer.Release, error) { + return installer.ResolveRelease(ctx, "", true) +} + func NewUpdateCmd() *cobra.Command { var f updateFlags @@ -117,9 +123,17 @@ func runUpdate(ctx context.Context, f updateFlags) error { src := &installer.GitHubManifestSource{} skills := splitAndTrim(f.skills) - // The plugin version recorded on update tracks the skills release. - // Tolerate a resolution error (skip plugin updates, still do skills). - ref, _, refErr := updateGetSkillsRefFn(ctx) + // The plugin version recorded on update tracks the skills release. When the + // latest release cannot be resolved, the plugins still update from the + // agent's marketplace and keep the version their records hold. refErr is + // set only when no release can be named at all; plugin updates are then + // skipped and the skills are still reconciled. + rel, refErr := updateResolveReleaseFn(ctx) + ref := rel.Ref + if rel.LookupErr != nil { + log.Debugf(ctx, "Recording plugin versions as unknown: %v", rel.LookupErr) + ref = "" + } // A failed or skipped plugin update, or a check whose manifest could // not be fetched, is only a warning, unless every attempt failed and @@ -372,9 +386,12 @@ func printPluginCheckResults(ctx context.Context, state *installer.InstallState, for _, name := range slices.Sorted(maps.Keys(state.Plugins)) { rec := state.Plugins[name] status := "up to date" - if rec.Version == "" { + switch { + case rec.Version == "": status = "update may be available" - } else if rec.Version != latest { + case latest == "": + status = "latest release unknown" + case rec.Version != latest: status = "update available" } cmdio.LogString(ctx, fmt.Sprintf(" %s databricks plugin %s (%s)", agentDisplayName(name), versionToken(rec.Version), status)) diff --git a/cmd/aitools/version.go b/cmd/aitools/version.go index e1d268487bf..76e63444ecb 100644 --- a/cmd/aitools/version.go +++ b/cmd/aitools/version.go @@ -49,9 +49,17 @@ func NewVersionCmd() *cobra.Command { return nil } - latestRef, _, err := installer.GetSkillsRef(ctx) - if err != nil { + // The fallback release is not the latest one, so an unresolved + // latest release shows no update line. + latestRef := "" + rel, err := installer.ResolveRelease(ctx, "", true) + switch { + case err != nil: log.Debugf(ctx, "could not resolve skills version: %v", err) + case rel.LookupErr != nil: + log.Debugf(ctx, "could not resolve the latest skills release: %v", rel.LookupErr) + default: + latestRef = rel.Ref } cmdio.LogString(ctx, "Databricks skills and plugins:") diff --git a/internal/build/README.md b/internal/build/README.md index 2b56946910c..08d4c628857 100644 --- a/internal/build/README.md +++ b/internal/build/README.md @@ -8,7 +8,7 @@ Raw skills track the latest published skills release for the newest CLI range. P ```json { - "1.22.0": { "appkit": "0.84.0", "skills": "latest" }, + "1.23.0": { "appkit": "0.84.0", "skills": "0.2.47", "use_latest": true }, "1.20.0": { "appkit": "0.84.0", "skills": "0.2.30" }, "1.0.0": { "appkit": "0.76.1", "skills": "0.2.10" }, "0.299.2": { "appkit": "0.24.0", "skills": "0.1.5" } @@ -17,7 +17,19 @@ Raw skills track the latest published skills release for the newest CLI range. P Each key is a CLI version in semver format. Each entry defines a **range floor**: it applies to that CLI version and all versions above it, up to (but not including) the next entry. The manifest should be **sparse** — not every CLI version needs its own entry. Only add a new entry when a compatibility boundary changes. -`skills` is an exact pin for its CLI range or `"latest"` to install the skills repository's latest published GitHub release. When the latest-release lookup fails or the selected skills manifest is missing, ranges tracking latest use `AgentSkillsFallbackVersion` from `internal/build/clicompat.go`. Pinned ranges use their embedded manifest's skills version as the fallback. Changing either fallback takes effect in the next CLI build. Released binaries keep the fallback they shipped with. +`skills` is always a concrete release. Without `use_latest` it is an exact pin for its CLI range. With `"use_latest": true` the range installs the skills repository's latest published release, and `skills` is the release to fall back to. CLIs that predate the field ignore it and install the pin, so the published manifest stays valid for every released CLI. Do not write `"skills": "latest"`: CLIs before `1.6.0` reject the whole manifest when any entry uses that sentinel, and CLIs from `1.6.0` to `1.28.0` would look the latest release up through the rate-limited GitHub API. The CLI still reads the sentinel from manifests cached before `use_latest` existed. + +A range with `use_latest` receives each skills release as soon as it is published, without a separate eval gate in the CLI. That is a deliberate choice: the skills repository owns the quality of its releases. A skill that needs a newer CLI should set `min_cli_version`, which the CLI enforces. Pinning a range without `use_latest` remains the way to hold CLIs back on a known release. + +### How the latest release is resolved + +A CLI whose range tracks latest reads `metaplugin/version.meta.json` from the skills repository's `main` branch on raw.githubusercontent.com, the host that serves the skill files. The skills release workflow records the version it releases there, before it pushes the tag, so the file can name a release whose tag does not exist yet. The CLI uses that release only once the host serves its `manifest.json`; until then the lookup counts as failed. The GitHub REST API is not used: its unauthenticated requests are limited per IP, and shared CI runners exhaust the limit (this failed `aitools list` with HTTP 403 in October 2026). + +When that lookup fails, the command does not fail. It uses the newest of four releases: the range's `skills` pin, the embedded manifest's pin, the release that was the latest when the CLI was built, and the installed release. The fallback therefore never downgrades an installation. Commands say so: `aitools install`, `update` and `list` warn and continue, `aitools version` shows no update line, `update --check` reports that nothing could be checked, and plugin records say "version unknown". The only exception is an installation the CLI cannot compare with a release (a legacy install without state, or one from a branch), which keeps failing on the lookup rather than overwrite it. + +The release known at build time can be injected with `-ldflags -X` into `internal/build/clicompat.go`. A build that injects nothing, and every development build, knows no such release; the fallback is then the manifest pin. + +Every CLI version on a machine shares the local cache. CLIs up to `1.28.0` re-encode the manifest when they refresh the cache and drop the fields they do not know, `use_latest` included, so a newer CLI that reads such a cache sees a pin until it refreshes the cache itself, at most an hour later. It does not install a pin older than the installed release: a compatibility pin never downgrades installed skills, and a deliberate downgrade takes `DATABRICKS_SKILLS_REF`. Newer CLIs write the manifest as fetched, so the field survives. An entry can also set `"auto_install": true` to turn on the automatic installation of Databricks AI tools on the first run of a new CLI version in its range (`aitools auto-install`). It is off when absent. A change reaches a machine on its first run of a CLI version after the change; machines that resolve to a cached or embedded manifest keep the value they have. @@ -27,16 +39,13 @@ This skills fallback only applies to raw-file delivery. Version checks omit upda Raw-skills updates and reinstalls reject automatic downgrades, including with `--force`: the fallback must be at least as new as the installed release. Existing installs without a comparable release require a successful latest-release fetch. Explicit `DATABRICKS_SKILLS_REF` overrides and compatibility pins can still select an older release, except in automatic installation: it keeps an installed release newer than the pinned one, which `databricks aitools update` still installs. -CLIs before `1.6.0` reject the whole remote manifest when any entry uses `"latest"`, even an entry they never resolve to. They use a valid cached manifest or their embedded manifest without returning a parse error. These CLIs stop receiving remote compatibility updates for both AppKit and skills. - -Latest tracking starts at the CLI `1.22.0` range. CLI `1.20.x` and `1.21.x` stay pinned. - For example, with the manifest above: - CLI `0.299.5` → uses `0.299.2` entry (appkit `0.24.0`) - CLI `1.19.0` → uses `1.0.0` entry (appkit `0.76.1`) - CLI `1.21.0` → uses `1.20.0` entry (appkit `0.84.0`, skills `0.2.30`) -- CLI `1.22.0` → uses `1.22.0` entry (appkit `0.84.0`, latest skills with compiled fallback `0.2.30`) -- CLI `0.0.0-dev+abc` → uses `1.22.0` entry (dev builds use the highest versioned entry) +- CLI `1.23.0` to `1.28.0` → uses `1.23.0` entry; these CLIs predate `use_latest` and install skills `0.2.47` +- CLI `1.29.0` → uses `1.23.0` entry (appkit `0.84.0`, latest skills, falling back to the newest of `0.2.47` and the release known at build time) +- CLI `0.0.0-dev+abc` → uses `1.23.0` entry (dev builds use the highest versioned entry) ## How the CLI resolves versions @@ -59,14 +68,14 @@ Set `DATABRICKS_FORCE_EMBEDDED_COMPAT=true` to skip all tiers and use only the e ## When to update -The goal is to **keep the manifest sparse** — only add entries at compatibility boundaries. Routine skills releases do not require a manifest update: keep `"skills": "latest"` on the newest range. +The goal is to **keep the manifest sparse** — only add entries at compatibility boundaries. Routine skills releases do not require a manifest update: keep `"use_latest": true` on the newest range. Its `skills` pin is the fallback, and also what CLIs from before `use_latest` install, so bump it now and then to a tested release. -When updating AppKit or recording a tested skills fallback: +When updating AppKit or the skills pin: 1. **Run evals** on the new AppKit version. If there is no regression, proceed. 2. **Open a PR** to update `cli-compat.json`. The change depends on the type of release: - - **No breaking changes**: update the highest entry's `appkit` in-place, keeping `"skills": "latest"`. To record a tested skills fallback, update `AgentSkillsFallbackVersion` in `internal/build/clicompat.go`. Do NOT add a new versioned key. - - **Breaking changes** (the new AppKit templates require specific `apps init` features, or the new skills version requires CLI commands that older CLIs lack): add a new entry keyed to the **minimum CLI version** that supports the new features. Set `"skills": "latest"` on the new entry and update the compiled skills fallback to a tested release. If skills compatibility changed, replace `"latest"` in the affected older ranges with the last compatible release. Preserve unrelated AppKit and skills compatibility boundaries. If the previous highest entry sets `"auto_install": true`, copy it to the new entry: a new entry without it turns auto-install off for every newer CLI. Do the same for `"skills_hints": true`, which turns skill hints on for its range. + - **No breaking changes**: update the highest entry's `appkit` or `skills` in-place, keeping `"use_latest": true`. Do NOT add a new versioned key. + - **Breaking changes** (the new AppKit templates require specific `apps init` features, or the new skills version requires CLI commands that older CLIs lack): add a new entry keyed to the **minimum CLI version** that supports the new features. Set `"use_latest": true` and a tested `skills` pin on the new entry. If skills compatibility changed, drop `use_latest` from the affected older ranges and pin them to the last compatible release. Preserve unrelated AppKit and skills compatibility boundaries. If the previous highest entry sets `"auto_install": true`, copy it to the new entry: a new entry without it turns auto-install off for every newer CLI. Do the same for `"skills_hints": true`, which turns skill hints on for its range. This process is manual for now but can be automated as part of the release workflow in the future. Use the `/bump-cli-compat` Claude Code skill to automate the update and PR creation. @@ -78,7 +87,21 @@ The manifest is validated by Go tests in `libs/clicompat/`: go test ./libs/clicompat/... -run TestEmbeddedManifest -v ``` -This checks: valid JSON, at least one entry, valid semver keys and AppKit versions, concrete skills versions or `"latest"`, a concrete compiled skills fallback, and latest tracking on the newest CLI range. +This checks: valid JSON, at least one entry, valid semver keys and AppKit versions, a concrete skills version on every entry (never the `"latest"` sentinel), and a concrete compiled skills fallback. + +## Verifying a manifest change against released CLIs + +Every CLI that fetches the manifest parses the whole file, so a value form that one released parser rejects freezes that CLI on its cache or embedded copy. Before publishing a change that adds a field or a new value form, build the oldest release that has `libs/clicompat` and the newest release that predates the change, plant the new manifest as a fresh cache, and run a command that resolves it with the skills host pointed at a closed port, so the only question is whether the parser accepts the file: + +```bash +git worktree add --detach /tmp/cli-v1.0.0 v1.0.0 && (cd /tmp/cli-v1.0.0 && go build -o /tmp/databricks-v1.0.0 .) +export DATABRICKS_CACHE_DIR=$(mktemp -d) HOME=$(mktemp -d) +mkdir -p "$HOME/.cursor" +cp internal/build/cli-compat.json "$DATABRICKS_CACHE_DIR/compat-manifest.json" +DATABRICKS_SKILLS_BASE_URL=http://127.0.0.1:1 /tmp/databricks-v1.0.0 aitools install --scope=global --agents=cursor --debug 2>&1 | grep -E 'manifest|skills version' +``` + +`Using cached manifest` followed by the expected `Using skills version` means the old parser accepted the file. `Fetching compatibility manifest` followed by `Using embedded manifest` means it rejected it. A manifest with `"skills": "latest"` shows the rejection on v1.0.0 and is a good control. ## Pruning policy diff --git a/internal/build/clicompat.go b/internal/build/clicompat.go index 3142eee1b22..a53b047d4f5 100644 --- a/internal/build/clicompat.go +++ b/internal/build/clicompat.go @@ -1,10 +1,28 @@ package build -import _ "embed" +import ( + _ "embed" -// AgentSkillsFallbackVersion is the tested release used when fetching the latest -// skills release fails. Updating it requires a new CLI build. -const AgentSkillsFallbackVersion = "0.2.30" + "golang.org/x/mod/semver" +) + +// agentSkillsFallbackVersion is the skills release that was the latest when the +// binary was built. Release builds can set it with -ldflags -X from the version +// the skills repository publishes. It is empty in development builds and when +// the release build did not set it. +var agentSkillsFallbackVersion string + +// AgentSkillsFallbackVersion is the skills release that was the latest when the +// binary was built, or "" when none is known. A CLI that tracks the latest +// release but cannot look it up installs the newer of this release and the +// pin of its compatibility manifest entry, so the pin is the checked-in +// fallback and this release only ever moves it forward. +func AgentSkillsFallbackVersion() string { + if semver.IsValid("v" + agentSkillsFallbackVersion) { + return agentSkillsFallbackVersion + } + return "" +} // CLICompatManifestJSON is the cli-compat.json manifest embedded at compile time. // Used as the last-resort fallback when both remote fetch and local cache fail. diff --git a/internal/build/clicompat_test.go b/internal/build/clicompat_test.go new file mode 100644 index 00000000000..d5b8c9164a9 --- /dev/null +++ b/internal/build/clicompat_test.go @@ -0,0 +1,27 @@ +package build + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestAgentSkillsFallbackVersion(t *testing.T) { + orig := agentSkillsFallbackVersion + t.Cleanup(func() { agentSkillsFallbackVersion = orig }) + + for _, tc := range []struct { + name string + built string + want string + }{ + {name: "development build", built: "", want: ""}, + {name: "release at build time", built: "0.2.57", want: "0.2.57"}, + {name: "not a version", built: "latest", want: ""}, + } { + t.Run(tc.name, func(t *testing.T) { + agentSkillsFallbackVersion = tc.built + assert.Equal(t, tc.want, AgentSkillsFallbackVersion()) + }) + } +} diff --git a/libs/aitools/installer/dump.go b/libs/aitools/installer/dump.go index 2a8f0ebbcda..8b18bc58538 100644 --- a/libs/aitools/installer/dump.go +++ b/libs/aitools/installer/dump.go @@ -18,13 +18,14 @@ import ( // the cli-compat version pin, --skills cherry-picks, and --experimental exactly // as the agent install path does, since it reuses resolveSkills. func DumpSkillsToPath(ctx context.Context, src ManifestSource, destDir string, opts InstallOptions) (int, error) { - ref, explicit, err := skills.ResolveSkillsRef(ctx, true) + rel, err := skills.ResolveRelease(ctx, "", true) if err != nil { return 0, err } - cmdio.LogString(ctx, "Using skills version "+DisplaySkillsVersion(ref)) + WarnLookupFallback(ctx, rel) + cmdio.LogString(ctx, "Using skills version "+DisplaySkillsVersion(rel.Ref)) - manifest, ref, err := FetchSkillsManifestWithFallback(ctx, src, ref, !explicit) + manifest, ref, err := FetchSkillsManifestWithFallback(ctx, src, rel.Ref, !rel.Pinned) if err != nil { return 0, err } diff --git a/libs/aitools/installer/installer.go b/libs/aitools/installer/installer.go index 7cd3576535d..293ac8d9a81 100644 --- a/libs/aitools/installer/installer.go +++ b/libs/aitools/installer/installer.go @@ -73,10 +73,21 @@ func DisplaySkillsVersion(ref string) string { return strings.TrimPrefix(ref, "v") } -// GetSkillsRef returns the skills ref to install from and whether it was -// explicitly pinned. See skills.GetSkillsRef. -func GetSkillsRef(ctx context.Context) (ref string, explicit bool, err error) { - return skills.GetSkillsRef(ctx) +// Release is the skills release a command works with. See skills.Release. +type Release = skills.Release + +// ResolveRelease returns the skills release to install from. See +// skills.ResolveRelease. +func ResolveRelease(ctx context.Context, installedRef string, allowFallback bool) (Release, error) { + return skills.ResolveRelease(ctx, installedRef, allowFallback) +} + +// WarnLookupFallback tells the user when a command works with the fallback +// release because the latest one could not be resolved. +func WarnLookupFallback(ctx context.Context, rel Release) { + if rel.LookupErr != nil { + log.Warnf(ctx, "Could not resolve the latest skills release (%v); using %s", rel.LookupErr, DisplaySkillsVersion(rel.Ref)) + } } // GetSkillsBaseURL returns the manifest and skill fetch base URL. @@ -265,17 +276,18 @@ func InstallSkillsForAgents(ctx context.Context, src ManifestSource, targetAgent installedRef, allowFallback := installedSkillsRelease(state) allowFallback = allowFallback && !legacyInstall - ref, explicit, err := skills.ResolveSkillsRef(ctx, allowFallback) + rel, err := skills.ResolveRelease(ctx, installedRef, allowFallback) if err != nil { return err } - cmdio.LogProgress(ctx, "Using skills version "+DisplaySkillsVersion(ref)) + WarnLookupFallback(ctx, rel) + cmdio.LogProgress(ctx, "Using skills version "+DisplaySkillsVersion(rel.Ref)) cmdio.LogProgress(ctx, "Fetching skills manifest...") - manifest, ref, err := FetchSkillsManifestWithFallback(ctx, src, ref, allowFallback && !explicit) + manifest, ref, err := FetchSkillsManifestWithFallback(ctx, src, rel.Ref, allowFallback && !rel.Pinned) if err != nil { return err } - if err := checkSkillsDowngrade(installedRef, ref, explicit); err != nil { + if err := checkSkillsDowngrade(installedRef, ref, rel.Pinned); err != nil { return err } diff --git a/libs/aitools/installer/installer_test.go b/libs/aitools/installer/installer_test.go index 65e6a7995d8..213e69e4717 100644 --- a/libs/aitools/installer/installer_test.go +++ b/libs/aitools/installer/installer_test.go @@ -692,14 +692,16 @@ func TestInstallSkillsForAgentsRecordsSkillsOnlyAgents(t *testing.T) { func setupSkillsFallback(t *testing.T, latestErr error) (ManifestSource, string) { t.Helper() - setBuildVersion(t, "1.22.0") + setBuildVersion(t, "1.23.0") t.Setenv("DATABRICKS_SKILLS_REF", "") t.Setenv("DATABRICKS_FORCE_EMBEDDED_COMPAT", "false") t.Setenv("DATABRICKS_CACHE_ENABLED", "true") - withCachedCompat(t, clicompat.AgentSkillsLatest) - stubLatestSkillsReleaseRef(t, "v9.9.9", latestErr) + // The cached manifest tracks latest with the embedded release as its pin, + // so a failed lookup and a missing manifest fall back to the same release. fallbackVersion, err := clicompat.ResolveEmbeddedAgentSkillsVersion() require.NoError(t, err) + withCachedCompatLatest(t, fallbackVersion) + stubLatestSkillsReleaseRef(t, "v9.9.9", latestErr) fallbackRef := "v" + fallbackVersion body, err := json.Marshal(testManifest()) require.NoError(t, err) @@ -827,9 +829,14 @@ func testSkillsRefSelection(t *testing.T, run func(context.Context, ManifestSour envPin bool compatPin bool wantErr bool + // keepInstalled marks a selection that keeps the installed release. + keepInstalled bool }{ {name: "environment pin", installedRef: "v9.9.8", selectedRef: testSkillsRef, envPin: true}, - {name: "compatibility pin", installedRef: "v9.9.8", selectedRef: testSkillsRef, compatPin: true}, + // An older CLI on the machine can rewrite the shared cache without + // use_latest, so an older compatibility pin must not downgrade. + {name: "older compatibility pin", installedRef: "v9.9.8", selectedRef: testSkillsRef, compatPin: true, keepInstalled: true}, + {name: "newer compatibility pin", installedRef: testSkillsRef, selectedRef: "v9.9.8", compatPin: true}, {name: "latest after branch", installedRef: "main", selectedRef: "v9.9.9"}, {name: "older latest release", installedRef: "v9.9.8", selectedRef: testSkillsRef, wantErr: true}, } { @@ -865,10 +872,13 @@ func testSkillsRefSelection(t *testing.T, run func(context.Context, ManifestSour } state, err := LoadState(filepath.Join(tmp, ".databricks", "aitools", "skills")) require.NoError(t, err) - if tc.wantErr { + switch { + case tc.wantErr: assert.Equal(t, tc.installedRef, state.Release) assert.Equal(t, version, state.Skills["databricks-sql"]) - } else { + case tc.keepInstalled: + assert.Equal(t, tc.installedRef, state.Release) + default: assert.Equal(t, tc.selectedRef, state.Release) assert.Equal(t, "0.1.0", state.Skills["databricks-sql"]) } @@ -1684,88 +1694,113 @@ func TestProjectScopeCapabilitiesSetCorrectly(t *testing.T) { } } -func TestGetSkillsRefDefaultsToLatest(t *testing.T) { - // cli-compat reports "latest", so we resolve it to the skills repo's - // latest release tag rather than tracking the default branch. +func TestResolveReleaseDefaultsToLatest(t *testing.T) { + // cli-compat tracks latest, so we resolve the skills repo's latest release + // tag rather than tracking the default branch. Both spellings track it: the + // "latest" sentinel of older manifests and "use_latest" next to a pin. t.Setenv("DATABRICKS_SKILLS_REF", "") - withCachedCompat(t, clicompat.AgentSkillsLatest) stubLatestSkillsReleaseRef(t, "v0.2.8", nil) + for name, cache := range map[string]func(*testing.T){ + "latest sentinel": func(t *testing.T) { withCachedCompat(t, clicompat.AgentSkillsLatest) }, + "use_latest": func(t *testing.T) { withCachedCompatLatest(t, "0.1.0") }, + } { + t.Run(name, func(t *testing.T) { + cache(t) - ref, explicit, err := GetSkillsRef(t.Context()) - require.NoError(t, err) - assert.Equal(t, "v0.2.8", ref) - assert.False(t, explicit, "tracking latest is not an explicit pin") + rel, err := ResolveRelease(t.Context(), "", true) + require.NoError(t, err) + assert.Equal(t, "v0.2.8", rel.Ref) + assert.False(t, rel.Pinned, "tracking latest is not an explicit pin") + assert.NoError(t, rel.LookupErr) + }) + } } -func TestGetSkillsRefDefaultManifest(t *testing.T) { +func TestResolveReleaseDefaultManifest(t *testing.T) { var m clicompat.Manifest require.NoError(t, json.Unmarshal(build.CLICompatManifestJSON, &m)) - // The table only records which CLI versions track latest. Pins come from - // the embedded manifest so routine skills bumps need no test changes. - tests := []struct { - version string - latest bool - }{ - {version: "0.299.2"}, - {version: "1.0.0"}, - {version: "1.19.9"}, - {version: "1.20.0"}, - {version: "1.21.0"}, - {version: "1.21.9"}, - {version: "1.22.0"}, - {version: "1.23.0"}, - {version: "0.0.0-dev+test"}, - } - for _, tc := range tests { - entry, err := clicompat.Resolve(m, tc.version) + // Whether a range tracks latest and its pin come from the embedded manifest, + // so routine skills bumps need no test changes. + for _, version := range []string{"0.299.2", "1.0.0", "1.19.9", "1.20.0", "1.21.0", "1.21.9", "1.22.0", "1.23.0", "0.0.0-dev+test"} { + entry, err := clicompat.Resolve(m, version) require.NoError(t, err) - pinnedRef := "v" + entry.AgentSkills + latest := entry.UseLatest || entry.AgentSkills == clicompat.AgentSkillsLatest for _, offline := range []bool{false, true} { - t.Run(fmt.Sprintf("%s/offline=%t", tc.version, offline), func(t *testing.T) { + t.Run(fmt.Sprintf("%s/offline=%t", version, offline), func(t *testing.T) { t.Setenv("DATABRICKS_SKILLS_REF", "") - setBuildVersion(t, tc.version) + setBuildVersion(t, version) cacheDir := t.TempDir() t.Setenv("DATABRICKS_CACHE_DIR", cacheDir) require.NoError(t, os.WriteFile(filepath.Join(cacheDir, "compat-manifest.json"), build.CLICompatManifestJSON, 0o600)) - wantRef := pinnedRef var latestErr error if offline { latestErr = errors.New("HTTP 403 fetching latest skills release") } - switch { - case tc.latest && offline: - wantRef = "" - case tc.latest: - wantRef = "v9.9.9" - } stubLatestSkillsReleaseRef(t, "v9.9.9", latestErr) - ref, explicit, err := GetSkillsRef(t.Context()) - if tc.latest && offline { - require.ErrorIs(t, err, latestErr) - } else { - require.NoError(t, err) + rel, err := ResolveRelease(t.Context(), "", true) + require.NoError(t, err) + switch { + case latest && offline: + assert.Equal(t, clicompat.NewestRelease(entry.AgentSkills, build.AgentSkillsFallbackVersion()), rel.Ref) + assert.False(t, rel.Pinned) + assert.ErrorIs(t, rel.LookupErr, latestErr) + case latest: + assert.Equal(t, "v9.9.9", rel.Ref) + assert.False(t, rel.Pinned) + assert.NoError(t, rel.LookupErr) + default: + assert.Equal(t, "v"+entry.AgentSkills, rel.Ref) + assert.True(t, rel.Pinned) + assert.NoError(t, rel.LookupErr) } - assert.Equal(t, wantRef, ref) - assert.Equal(t, !tc.latest, explicit) }) } } } -func TestGetSkillsRefLatestReleaseLookupFails(t *testing.T) { +func TestResolveReleaseLatestReleaseLookupFails(t *testing.T) { setBuildVersion(t, "1.22.0") t.Setenv("DATABRICKS_SKILLS_REF", "") - withCachedCompat(t, clicompat.AgentSkillsLatest) latestErr := errors.New("network down") stubLatestSkillsReleaseRef(t, "", latestErr) + // The embedded manifest pins this CLI, and a development build knows no + // release from build time, so the embedded pin is the floor of the fallback. + embedded, err := clicompat.ResolveEmbeddedAgentSkillsVersion() + require.NoError(t, err) + embeddedRef := "v" + embedded - ref, explicit, err := GetSkillsRef(t.Context()) - require.ErrorIs(t, err, latestErr) - assert.Empty(t, ref, "the embedded fallback is not the latest release") - assert.False(t, explicit) + for _, tc := range []struct { + name string + pin string // "" for the "latest" sentinel + installedRef string + wantRef string + }{ + {name: "sentinel falls back to the embedded release", wantRef: embeddedRef}, + {name: "older pin falls back to the embedded release", pin: "0.0.1", wantRef: embeddedRef}, + {name: "newer pin wins", pin: "9.9.9", wantRef: "v9.9.9"}, + {name: "newer installed release wins", pin: "0.0.1", installedRef: "v9.9.8", wantRef: "v9.9.8"}, + } { + t.Run(tc.name, func(t *testing.T) { + if tc.pin == "" { + withCachedCompat(t, clicompat.AgentSkillsLatest) + } else { + withCachedCompatLatest(t, tc.pin) + } + + rel, err := ResolveRelease(t.Context(), tc.installedRef, true) + require.NoError(t, err, "a failed lookup falls back instead of failing") + assert.Equal(t, tc.wantRef, rel.Ref) + assert.False(t, rel.Pinned, "the fallback is not a pin") + assert.ErrorIs(t, rel.LookupErr, latestErr) + + // Without the fallback, the lookup error is returned. + _, err = ResolveRelease(t.Context(), tc.installedRef, false) + require.ErrorIs(t, err, latestErr) + }) + } } func TestFetchSkillsManifestWithFallback(t *testing.T) { @@ -1814,25 +1849,23 @@ func TestFetchSkillsManifestWithFallback(t *testing.T) { } } -func TestGetSkillsRefEnvEscapeHatch(t *testing.T) { +func TestResolveReleaseEnvEscapeHatch(t *testing.T) { t.Setenv("DATABRICKS_SKILLS_REF", "v9.9.9") - ref, explicit, err := GetSkillsRef(t.Context()) + rel, err := ResolveRelease(t.Context(), "", true) require.NoError(t, err) - assert.Equal(t, "v9.9.9", ref) - assert.True(t, explicit, "an explicit ref is a pin") + assert.Equal(t, Release{Ref: "v9.9.9", Pinned: true}, rel, "an explicit ref is a pin") } -func TestGetSkillsRefPinnedByCliCompat(t *testing.T) { +func TestResolveReleasePinnedByCliCompat(t *testing.T) { // cli-compat reports a concrete version: the remote safety valve pinning this // CLI (e.g. after a future breaking change). t.Setenv("DATABRICKS_SKILLS_REF", "") withCachedCompat(t, "0.1.5") - ref, explicit, err := GetSkillsRef(t.Context()) - require.NoError(t, err, "GetSkillsRef should succeed via cached manifest") - assert.Equal(t, "v0.1.5", ref) - assert.True(t, explicit, "a cli-compat pin is explicit") + rel, err := ResolveRelease(t.Context(), "", true) + require.NoError(t, err, "ResolveRelease should succeed via cached manifest") + assert.Equal(t, Release{Ref: "v0.1.5", Pinned: true}, rel, "a cli-compat pin is explicit") } func TestDisplaySkillsVersion(t *testing.T) { @@ -1852,6 +1885,58 @@ func withCachedCompat(t *testing.T, skills string) { require.NoError(t, os.WriteFile(filepath.Join(cacheDir, "compat-manifest.json"), []byte(manifest), 0o644)) } +// withCachedCompatLatest is withCachedCompat for a manifest that tracks the +// latest release, with fallback as the release to fall back to. +func withCachedCompatLatest(t *testing.T, fallback string) { + t.Helper() + cacheDir := t.TempDir() + t.Setenv("DATABRICKS_CACHE_DIR", cacheDir) + manifest := fmt.Sprintf(`{"0.0.0":{"appkit":"0.24.0","skills":%q,"use_latest":true}}`, fallback) + require.NoError(t, os.WriteFile(filepath.Join(cacheDir, "compat-manifest.json"), []byte(manifest), 0o644)) +} + +func TestFetchLatestSkillsReleaseRef(t *testing.T) { + for _, tc := range []struct { + name string + published bool + }{ + {name: "published release", published: true}, + // The version file runs ahead of the tags while a release is cut. + {name: "release without a tag yet"}, + } { + t.Run(tc.name, func(t *testing.T) { + var paths []string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + paths = append(paths, r.URL.Path) + switch { + case r.URL.Path == "/main/metaplugin/version.meta.json": + _, _ = w.Write([]byte(`{"current_version": "0.2.57", "next_version": "0.2.58"}`)) + case tc.published: + _, _ = w.Write([]byte(`{}`)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(server.Close) + t.Setenv("DATABRICKS_SKILLS_BASE_URL", server.URL) + + ref, err := skills.FetchLatestSkillsReleaseRef(t.Context()) + // The version file the skills release workflow writes, read from + // the host that serves the skill files rather than the + // rate-limited GitHub API, then the release's manifest. + assert.Equal(t, []string{"/main/metaplugin/version.meta.json", "/v0.2.57/manifest.json"}, paths) + if tc.published { + require.NoError(t, err) + assert.Equal(t, "v0.2.57", ref) + return + } + ferr, ok := errors.AsType[*FetchError](err) + require.True(t, ok, "want *FetchError, got %T", err) + assert.Equal(t, FetchStageRelease, ferr.Stage, "an untagged release is a failed lookup, so the fallback runs") + }) + } +} + func TestFetchLatestSkillsReleaseRefRateLimited(t *testing.T) { tests := []struct { name string @@ -1875,7 +1960,7 @@ func TestFetchLatestSkillsReleaseRefRateLimited(t *testing.T) { w.WriteHeader(tc.status) })) t.Cleanup(server.Close) - t.Setenv("DATABRICKS_CLI_GITHUB_API_URL", server.URL) + t.Setenv("DATABRICKS_SKILLS_BASE_URL", server.URL) _, err := skills.FetchLatestSkillsReleaseRef(t.Context()) ferr, ok := errors.AsType[*FetchError](err) @@ -1894,8 +1979,8 @@ func TestFetchLatestSkillsReleaseRefUnusableResponse(t *testing.T) { }{ {name: "HTML page", body: "login"}, {name: "empty body", body: ""}, - {name: "empty tag_name", body: `{"tag_name": ""}`}, - {name: "invalid tag", body: `{"tag_name": "not-a-version"}`}, + {name: "empty current_version", body: `{"current_version": ""}`}, + {name: "invalid version", body: `{"current_version": "not-a-version"}`}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -1903,7 +1988,7 @@ func TestFetchLatestSkillsReleaseRefUnusableResponse(t *testing.T) { _, _ = w.Write([]byte(tc.body)) })) t.Cleanup(server.Close) - t.Setenv("DATABRICKS_CLI_GITHUB_API_URL", server.URL) + t.Setenv("DATABRICKS_SKILLS_BASE_URL", server.URL) _, err := skills.FetchLatestSkillsReleaseRef(t.Context()) ferr, ok := errors.AsType[*FetchError](err) diff --git a/libs/aitools/installer/plugin_test.go b/libs/aitools/installer/plugin_test.go index 1582dbc6bc8..38f7b9c5e17 100644 --- a/libs/aitools/installer/plugin_test.go +++ b/libs/aitools/installer/plugin_test.go @@ -1085,3 +1085,32 @@ func TestStderrOf(t *testing.T) { assert.Equal(t, "boom", stderrOf(failed)) assert.Equal(t, exec.ErrNotFound.Error(), stderrOf(exec.ErrNotFound)) } + +// A failed lookup of the latest release leaves the ref empty. The record keeps +// the version it holds: turning it unknown would read as a change, and the +// auto-install notice would report an update after an unrelated command. +func TestUpdateInstalledPluginsKeepsVersionWhenReleaseUnknown(t *testing.T) { + setupTestHome(t) + stubAgentLookPath(t, true) + ctx, stub := process.WithStub(t.Context()) + stub.WithCallback(func(*exec.Cmd) error { return nil }) + + dir, err := GlobalSkillsDir(ctx) + require.NoError(t, err) + require.NoError(t, SaveState(dir, &InstallState{ + SchemaVersion: CurrentSchemaVersion, + Release: "v0.2.56", + Plugins: map[string]PluginRecord{ + agents.NameClaudeCode: {Marketplace: "claude-plugins-official", Plugin: "databricks", Scope: "user", Version: "0.2.56"}, + }, + })) + + updated, err := UpdateInstalledPlugins(ctx, ScopeGlobal, "") + require.NoError(t, err) + require.Len(t, updated, 1) + require.NoError(t, updated[0].Err) + assert.Equal(t, "0.2.56", updated[0].Version) + state, err := LoadState(dir) + require.NoError(t, err) + assert.Equal(t, "0.2.56", state.Plugins[agents.NameClaudeCode].Version) +} diff --git a/libs/aitools/installer/update.go b/libs/aitools/installer/update.go index 4cce785b707..8e1ac88b369 100644 --- a/libs/aitools/installer/update.go +++ b/libs/aitools/installer/update.go @@ -53,7 +53,8 @@ type UpdateResult struct { Removed []SkillUpdate // skills pruned because they vanished from the manifest Unchanged []string // skills at current version (or kept despite vanishing) Skipped []string // skills skipped (experimental, version constraint) - // CheckErr is set in check mode when the manifest could not be fetched: the + // CheckErr is set in check mode when the latest release could not be + // resolved or the manifest could not be fetched: the // check is skipped with a warning, so nothing was checked. CheckErr error } @@ -107,10 +108,17 @@ func UpdateSkills(ctx context.Context, src ManifestSource, targetAgents []*agent } installedRef, allowFallback := installedSkillsRelease(state) - latestTag, explicit, err := skills.ResolveSkillsRef(ctx, allowFallback) + rel, err := skills.ResolveRelease(ctx, installedRef, allowFallback) if err != nil { return nil, err } + if rel.LookupErr != nil && opts.Check { + // The check cannot tell whether a newer release exists. + log.Warnf(ctx, "Could not resolve the latest skills release: %v", rel.LookupErr) + return &UpdateResult{CheckErr: rel.LookupErr}, nil + } + WarnLookupFallback(ctx, rel) + latestTag, explicit := rel.Ref, rel.Pinned // Short-circuit only when pinned to an exact ref. When tracking latest (the // default), the ref ("main") never changes, so always reconcile against the @@ -559,9 +567,14 @@ func UpdateInstalledPlugins(ctx context.Context, scope, ref string) ([]PluginUpd // version is unknown, unless the record already holds this release: the // local copy can only have moved forward since the refresh that wrote it. // Warn only when the version is cleared, as install does. - if refreshErr == nil || rec.Version == version { + switch { + case version == "": + // The latest release could not be resolved, so the record keeps + // the version it holds rather than turn unknown, which would read + // as a change. + case refreshErr == nil || rec.Version == version: rec.Version = version - } else { + default: warnLocalMarketplaceCopy(ctx, agent, recordedMarketplace(agent, rec), "rerun `databricks aitools update` later", refreshErr) rec.Version = "" } diff --git a/libs/clicompat/clicompat.go b/libs/clicompat/clicompat.go index 2e8f93c15db..ead1a51deef 100644 --- a/libs/clicompat/clicompat.go +++ b/libs/clicompat/clicompat.go @@ -69,6 +69,32 @@ type Entry struct { // again) remotely. It is read from a fresh local cache only; see // internal/build/README.md. CLIs that predate the field ignore it. SkillsHints bool `json:"skills_hints,omitempty"` + + // UseLatest makes the range track the latest published skills release; + // AgentSkills is then the release to fall back to when the latest one cannot + // be resolved. CLIs that predate the field ignore it and install AgentSkills, + // which keeps the remote manifest valid for every released CLI, unlike the + // AgentSkillsLatest sentinel. + UseLatest bool `json:"use_latest,omitempty"` +} + +// AgentSkills is the skills selection of a manifest entry. +type AgentSkills struct { + // Version is the pinned release or, when TrackLatest is set, the release to + // fall back to when the latest one cannot be resolved. It is empty for an + // entry that uses the AgentSkillsLatest sentinel. + Version string + // TrackLatest reports whether the entry tracks the latest published skills + // release instead of pinning Version. + TrackLatest bool +} + +// agentSkills returns the entry's skills selection. +func (e Entry) agentSkills() AgentSkills { + if e.AgentSkills == AgentSkillsLatest { + return AgentSkills{TrackLatest: true} + } + return AgentSkills{Version: e.AgentSkills, TrackLatest: e.UseLatest} } // Manifest is the compatibility manifest: a map of CLI version strings to entries. @@ -129,10 +155,10 @@ func fetchManifest(ctx context.Context) (m Manifest, fallback bool, err error) { } // Tier 2: fetch from remote (local file missing or stale). - m, fetchErr := fetchRemoteWithRetry(ctx) + m, data, fetchErr := fetchRemoteWithRetry(ctx) if fetchErr == nil { if cacheEnabled(ctx) { - writeLocalManifest(ctx, localPath, m) + writeLocalManifest(ctx, localPath, data) } return m, false, nil } @@ -174,9 +200,10 @@ func ResolveEmbeddedAppKitVersion() (string, error) { return entry.AppKit, nil } -// ResolveEmbeddedAgentSkillsVersion resolves the fallback for the current CLI -// without fetching compatibility data. Ranges tracking latest use the tested -// release compiled into the binary. +// ResolveEmbeddedAgentSkillsVersion resolves the skills release to fall back to +// for the current CLI without fetching compatibility data: the embedded +// manifest's pin or, for a range that tracks latest, the newer of that pin and +// the release known at build time. func ResolveEmbeddedAgentSkillsVersion() (string, error) { m, err := parseEmbeddedManifest() if err != nil { @@ -186,10 +213,30 @@ func ResolveEmbeddedAgentSkillsVersion() (string, error) { if err != nil { return "", fmt.Errorf("embedded manifest resolve: %w", err) } - if entry.AgentSkills == AgentSkillsLatest { - return build.AgentSkillsFallbackVersion, nil + sel := entry.agentSkills() + if !sel.TrackLatest { + return sel.Version, nil } - return entry.AgentSkills, nil + return strings.TrimPrefix(NewestRelease(sel.Version, build.AgentSkillsFallbackVersion()), "v"), nil +} + +// NewestRelease returns the newest of the given releases by semver as a +// "v"-prefixed ref, ignoring empty and invalid ones. A release may be given +// with or without the leading "v". It returns "" when no release is valid. +func NewestRelease(releases ...string) string { + newest := "" + for _, r := range releases { + if r != "" && !strings.HasPrefix(r, "v") { + r = "v" + r + } + if !semver.IsValid(r) { + continue + } + if newest == "" || semver.Compare(r, newest) > 0 { + newest = r + } + } + return newest } // IsNotFoundError reports whether the error indicates a "not found" condition @@ -289,13 +336,13 @@ func ResolveAppKitVersion(ctx context.Context) (string, error) { return entry.AppKit, nil } -// ResolveAgentSkillsVersion resolves the Agent Skills version for the current CLI. -func ResolveAgentSkillsVersion(ctx context.Context) (string, error) { +// ResolveAgentSkills resolves the skills selection for the current CLI. +func ResolveAgentSkills(ctx context.Context) (AgentSkills, error) { entry, err := resolveEntry(ctx, build.GetInfo().Version) if err != nil { - return "", err + return AgentSkills{}, err } - return entry.AgentSkills, nil + return entry.agentSkills(), nil } // ResolveAutoInstall reports whether the manifest entry for cliVersion turns on @@ -410,18 +457,15 @@ func readLocalManifest(path string) (cachedManifest, error) { return cachedManifest{manifest: m, modTime: info.ModTime()}, nil } -// writeLocalManifest writes the manifest to the local cache path atomically. -// A CLI that predates a field re-encodes the cache when it refreshes it and -// drops the field; see internal/build/README.md. -func writeLocalManifest(ctx context.Context, path string, m Manifest) { +// writeLocalManifest writes the manifest as fetched to the local cache path +// atomically. Every CLI version on a machine shares the cache, so the bytes are +// kept as they are: a field this CLI does not know survives for a newer CLI +// that reads the cache. CLIs up to 1.28.0 re-encoded the manifest and dropped +// such fields; see internal/build/README.md. +func writeLocalManifest(ctx context.Context, path string, data []byte) { if path == "" { return } - data, err := json.Marshal(m) - if err != nil { - log.Debugf(ctx, "Failed to marshal manifest for cache: %v", err) - return - } if err := atomicfile.Write(path, data, 0o600, atomicfile.MkDir(0o700)); err != nil { log.Warnf(ctx, "Failed to write cache file: %v", err) } @@ -431,61 +475,69 @@ func writeLocalManifest(ctx context.Context, path string, m Manifest) { // fetchRemoteWithRetry wraps fetchRemote with retries on transient errors. // Client errors (4xx) are not retried since they will not recover. -func fetchRemoteWithRetry(ctx context.Context) (Manifest, error) { +func fetchRemoteWithRetry(ctx context.Context) (Manifest, []byte, error) { var lastErr error for attempt := range maxFetchAttempts { if attempt > 0 { log.Debugf(ctx, "Retrying manifest fetch (attempt %d/%d)", attempt+1, maxFetchAttempts) select { case <-ctx.Done(): - return nil, ctx.Err() + return nil, nil, ctx.Err() case <-time.After(fetchRetryBackoff): } } - m, err := fetchRemote(ctx) + m, data, err := fetchRemote(ctx) if err == nil { - return m, nil + return m, data, nil } lastErr = err // Do not retry client errors (4xx) — they won't resolve on retry. if httpErr, ok := errors.AsType[*HTTPStatusError](err); ok && httpErr.StatusCode >= 400 && httpErr.StatusCode < 500 { - return nil, lastErr + return nil, nil, lastErr } } - return nil, lastErr + return nil, nil, lastErr } -func fetchRemote(ctx context.Context) (Manifest, error) { +// fetchRemote fetches and parses the manifest, returning the parsed manifest +// together with the bytes as fetched, for the cache. +func fetchRemote(ctx context.Context) (Manifest, []byte, error) { log.Debugf(ctx, "Fetching compatibility manifest from %s", manifestURL) req, err := http.NewRequestWithContext(ctx, http.MethodGet, manifestURL, nil) if err != nil { - return nil, err + return nil, nil, err } req.Header.Set("User-Agent", "databricks-cli/"+build.GetInfo().Version) resp, err := httpClient.Do(req) if err != nil { - return nil, err + return nil, nil, err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - return nil, &HTTPStatusError{StatusCode: resp.StatusCode} + return nil, nil, &HTTPStatusError{StatusCode: resp.StatusCode} } // Cap response size to guard against corrupted or malicious responses. body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { - return nil, err + return nil, nil, err } - return parseManifest(body) + m, err := parseManifest(body) + if err != nil { + return nil, nil, err + } + return m, body, nil } // AgentSkillsLatest is the sentinel value the skills field may take instead of a // concrete version, meaning "track the latest skills" rather than pinning a -// release. The aitools installer maps it to the skills repo's latest release tag. +// release. It is kept for manifests cached before Entry.UseLatest existed; the +// published manifest must not use it, since CLIs before 1.6.0 reject the whole +// manifest when any entry does. Set "use_latest": true next to a pin instead. const AgentSkillsLatest = "latest" func parseManifest(data []byte) (Manifest, error) { diff --git a/libs/clicompat/clicompat_test.go b/libs/clicompat/clicompat_test.go index b02c3cad1f9..f8a8a0852a3 100644 --- a/libs/clicompat/clicompat_test.go +++ b/libs/clicompat/clicompat_test.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "slices" + "strings" "sync/atomic" "testing" "time" @@ -24,8 +25,6 @@ import ( "golang.org/x/mod/semver" ) -const pinnedAgentSkillsVersion = "0.2.47" - // roundTripFunc adapts a function into an http.RoundTripper. type roundTripFunc func(*http.Request) (*http.Response, error) @@ -296,14 +295,15 @@ func TestResolveEntry_RemoteFailUsesEmbedded(t *testing.T) { assert.NotEmpty(t, entry.AppKit) } -func TestResolveAgentSkillsVersion(t *testing.T) { +func TestResolveAgentSkills(t *testing.T) { tests := []struct { name string manifest string - want string + want AgentSkills }{ - {name: "pinned", manifest: `{"0.0.0":{"appkit":"0.84.0","skills":"0.2.30"}}`, want: "0.2.30"}, - {name: "latest sentinel", manifest: `{"0.0.0":{"appkit":"0.84.0","skills":"latest"}}`, want: AgentSkillsLatest}, + {name: "pinned", manifest: `{"0.0.0":{"appkit":"0.84.0","skills":"0.2.30"}}`, want: AgentSkills{Version: "0.2.30"}}, + {name: "latest sentinel", manifest: `{"0.0.0":{"appkit":"0.84.0","skills":"latest"}}`, want: AgentSkills{TrackLatest: true}}, + {name: "use_latest with a fallback pin", manifest: `{"0.0.0":{"appkit":"0.84.0","skills":"0.2.30","use_latest":true}}`, want: AgentSkills{Version: "0.2.30", TrackLatest: true}}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { @@ -314,13 +314,21 @@ func TestResolveAgentSkillsVersion(t *testing.T) { defer srv.Close() redirectToServer(t, srv) - v, err := ResolveAgentSkillsVersion(ctx) + sel, err := ResolveAgentSkills(ctx) require.NoError(t, err) - assert.Equal(t, tc.want, v) + assert.Equal(t, tc.want, sel) }) } } +func TestNewestRelease(t *testing.T) { + assert.Empty(t, NewestRelease()) + assert.Empty(t, NewestRelease("", "latest", "main")) + assert.Equal(t, "v0.2.47", NewestRelease("0.2.30", "0.2.47", "")) + assert.Equal(t, "v0.2.47", NewestRelease("v0.2.30", "0.2.47"), "releases may be given with or without the v") + assert.Equal(t, "v9.9.8", NewestRelease("0.2.47", "latest", "v9.9.8")) +} + func TestResolveAutoInstall(t *testing.T) { manifest := `{ "1.20.0": {"appkit": "0.84.0", "skills": "0.2.30"}, @@ -385,6 +393,16 @@ func TestResolveEmbeddedAppKitVersion(t *testing.T) { } func TestResolveEmbeddedAgentSkillsVersion(t *testing.T) { + var m Manifest + require.NoError(t, json.Unmarshal(build.CLICompatManifestJSON, &m)) + // The newest range's fallback is its pin or, once it tracks latest, the + // newer of its pin and the release known at build time. Read from the + // manifest so routine bumps need no test changes. + newest := m[sortedVersions(m)[0]] + wantNewest := newest.AgentSkills + if newest.UseLatest { + wantNewest = strings.TrimPrefix(NewestRelease(newest.AgentSkills, build.AgentSkillsFallbackVersion()), "v") + } for _, tc := range []struct { version string want string @@ -392,9 +410,9 @@ func TestResolveEmbeddedAgentSkillsVersion(t *testing.T) { {version: "1.0.0", want: "0.2.10"}, {version: "1.22.0", want: "0.2.32"}, {version: "1.22.1", want: "0.2.32"}, - {version: "1.23.0", want: pinnedAgentSkillsVersion}, - {version: "1.26.0", want: pinnedAgentSkillsVersion}, - {version: "0.0.0-dev+test", want: pinnedAgentSkillsVersion}, + {version: "1.23.0", want: wantNewest}, + {version: "1.26.0", want: wantNewest}, + {version: "0.0.0-dev+test", want: wantNewest}, } { t.Run(tc.version, func(t *testing.T) { original := build.GetInfo().Version @@ -427,12 +445,13 @@ func TestEmbeddedManifest_IsWellFormed(t *testing.T) { return semver.Compare("v"+a, "v"+b) }) - // Pinning the newest range (e.g. after a breaking skills release) must - // update this assertion in the same change. - assert.Equal(t, pinnedAgentSkillsVersion, m[keys[len(keys)-1]].AgentSkills, - "the newest CLI range must stay pinned until all callers support latest-release fallback") - assert.True(t, semver.IsValid("v"+build.AgentSkillsFallbackVersion), - "compiled skills fallback must be a concrete version") + // The published manifest must stay valid for every released CLI: CLIs + // before 1.6.0 reject the whole manifest when any entry uses the "latest" + // sentinel. A range tracks latest with "use_latest" next to its pin. + for _, k := range keys { + assert.True(t, semver.IsValid("v"+m[k].AgentSkills), + "entry %q must pin a skills release, not %q", k, m[k].AgentSkills) + } // Keys must be in ascending semver order. for i := 1; i < len(keys); i++ { @@ -453,18 +472,21 @@ func TestManifestLocalPath(t *testing.T) { func TestReadWriteLocalManifest(t *testing.T) { ctx := testContext(t) - m := Manifest{ - "0.300.0": {AppKit: "0.50.0", AgentSkills: "0.5.0", SkillsHints: true}, - } + data := []byte(`{"0.300.0": {"appkit": "0.50.0", "skills": "0.5.0", "skills_hints": true, "field_of_a_newer_cli": true}}`) path := manifestLocalPath(ctx) - writeLocalManifest(ctx, path, m) + writeLocalManifest(ctx, path, data) cached, err := readLocalManifest(path) require.NoError(t, err) assert.Equal(t, "0.50.0", cached.manifest["0.300.0"].AppKit) assert.True(t, cached.manifest["0.300.0"].SkillsHints) assert.True(t, cached.isFresh(cacheTTL), "just-written file should be fresh") + // Every CLI version on a machine shares the cache, so a field this CLI + // does not know must survive for a newer CLI that reads it. + raw, err := os.ReadFile(path) + require.NoError(t, err) + assert.Equal(t, data, raw, "the cache keeps the manifest as fetched") } // --- IsNotFoundError tests --- diff --git a/libs/skills/fetch.go b/libs/skills/fetch.go index 547518c913d..0e10a0856e3 100644 --- a/libs/skills/fetch.go +++ b/libs/skills/fetch.go @@ -16,7 +16,8 @@ var ErrManifestTooLarge = fmt.Errorf("skills manifest is larger than %d MiB", Ma // Stages of fetching skills content, recorded on FetchError so a failed // release lookup can be told apart from a failed download. const ( - // FetchStageRelease: resolving the latest skills release on api.github.com. + // FetchStageRelease: resolving the latest skills release from the version + // file the skills repo publishes. FetchStageRelease = "release" // FetchStageManifest: downloading the skills manifest. FetchStageManifest = "manifest" diff --git a/libs/skills/ref.go b/libs/skills/ref.go index 3491f855f90..59520e4e0f4 100644 --- a/libs/skills/ref.go +++ b/libs/skills/ref.go @@ -11,10 +11,10 @@ import ( "sync" "time" + "github.com/databricks/cli/internal/build" "github.com/databricks/cli/libs/clicompat" "github.com/databricks/cli/libs/env" "github.com/databricks/cli/libs/log" - "github.com/databricks/cli/libs/versioncheck" "golang.org/x/mod/semver" ) @@ -22,6 +22,15 @@ const ( // RepoOwner and RepoName locate the skills repo on GitHub. RepoOwner = "databricks" RepoName = "databricks-agent-skills" + + // latestReleasePointer is the file, on the skills repo's main branch, in + // which its release workflow records the version it releases. The workflow + // commits it before it pushes the tag, so it can name a release that has no + // tag yet; the lookup checks the tag. It is read from GetSkillsBaseURL, the + // host that serves the skill files, instead of the GitHub REST API: the API + // limits unauthenticated requests per IP, and shared CI runners exhaust the + // limit (HTTP 403). + latestReleasePointer = "main/metaplugin/version.meta.json" ) // FetchConcurrency caps the number of in-flight skill file fetches. @@ -50,71 +59,91 @@ var HTTPClient = sync.OnceValue(func() *http.Client { // replace it so default ref resolution stays deterministic and offline. var LatestSkillsReleaseRefFn = FetchLatestSkillsReleaseRef -// skillsLatestSentinel is the value cli-compat.json uses for the skills version -// to mean "track latest" rather than pinning a specific release. -const skillsLatestSentinel = clicompat.AgentSkillsLatest - -// GetSkillsRef returns the skills repo ref to use and whether it was explicitly -// pinned (as opposed to tracking latest). An unresolved latest release is an error. -// -// By default we track the latest skills release tag, not the skills repo's main -// branch. cli-compat.json is the remote control for this: its newest range -// normally tracks latest, but if a future change makes a skills release -// incompatible with older CLIs, it can be edited remotely to pin those CLIs to -// the last compatible version with no CLI release. DATABRICKS_SKILLS_REF -// overrides everything for eval/reproducibility. (AppKit version resolution is -// unaffected; cli-compat still manages it via its own field.) -func GetSkillsRef(ctx context.Context) (ref string, explicit bool, err error) { - return ResolveSkillsRef(ctx, false) +// Release is the skills release a command works with. +type Release struct { + // Ref is the git ref to read: a release tag such as "v0.2.57", or the + // branch or commit that DATABRICKS_SKILLS_REF names. + Ref string + // Pinned reports whether Ref was chosen explicitly, by DATABRICKS_SKILLS_REF + // or by a compatibility manifest entry that does not track latest. A release + // pinned by DATABRICKS_SKILLS_REF is installed even when it is older than + // the installed one. + Pinned bool + // LookupErr is set when the CLI tracks the latest release but could not + // resolve it. Ref is then the fallback: the newest of the compatibility + // manifest's release, the embedded manifest's release, the release known + // at build time and the installed one, so the fallback never downgrades + // an installation. + LookupErr error } -// ResolveSkillsRef is GetSkillsRef, except that with allowFallback a failed -// latest-release lookup falls back to the embedded cli-compat skills version -// when that version is a pinned release, logging a warning. The fallback ref is -// not explicit. When the embedded version is empty, "latest" or unreadable, the -// lookup error is returned as it would be without allowFallback. -func ResolveSkillsRef(ctx context.Context, allowFallback bool) (ref string, explicit bool, err error) { +// ResolveRelease returns the skills release to use. +// +// DATABRICKS_SKILLS_REF overrides everything, for evals and reproducibility. +// Otherwise cli-compat.json decides: an entry that pins a release is followed, +// and an entry that tracks latest resolves the skills repo's latest release +// tag. cli-compat.json is the remote control: if a skills release breaks older +// CLIs, their ranges can be pinned to the last compatible release with no CLI +// release. (AppKit version resolution is unaffected; cli-compat still manages +// it via its own field.) +// +// A failed latest-release lookup never fails the command on its own: with +// allowFallback, the fallback release is returned with LookupErr set. +// installedRef is the installed release, "v"-prefixed, or "" when nothing +// comparable is installed; it keeps the fallback from going below it. Without +// allowFallback the lookup error is returned, for callers that cannot tell +// whether the fallback would overwrite newer content. +func ResolveRelease(ctx context.Context, installedRef string, allowFallback bool) (Release, error) { if ref := env.Get(ctx, "DATABRICKS_SKILLS_REF"); ref != "" { - return ref, true, nil + return Release{Ref: ref, Pinned: true}, nil } - v, err := clicompat.ResolveAgentSkillsVersion(ctx) + sel, err := clicompat.ResolveAgentSkills(ctx) if err != nil { - log.Debugf(ctx, "could not resolve skills compatibility, resolving latest release: %v", err) - return resolveLatestSkillsReleaseRef(ctx, allowFallback) - } - if v == "" || v == skillsLatestSentinel { - return resolveLatestSkillsReleaseRef(ctx, allowFallback) - } - return "v" + v, true, nil -} - -func resolveLatestSkillsReleaseRef(ctx context.Context, allowFallback bool) (ref string, explicit bool, err error) { - ref, err = LatestSkillsReleaseRefFn(ctx) - if err == nil { - return ref, false, nil + // Without compatibility data the CLI tracks latest, with the release + // known at build time as the fallback. + log.Debugf(ctx, "could not resolve skills compatibility, tracking the latest release: %v", err) + sel = clicompat.AgentSkills{TrackLatest: true} + } + if !sel.TrackLatest { + pin := "v" + sel.Version + // A compatibility pin older than the installed release keeps the + // installed one. CLIs up to 1.28.0 share the manifest cache and drop + // use_latest when they rewrite it, so a pin there can be the fallback + // of a range that tracks latest, and following it would downgrade the + // skills each time an older CLI refreshes the cache. Downgrading on + // purpose takes DATABRICKS_SKILLS_REF. + if semver.IsValid(installedRef) && semver.Compare(pin, installedRef) < 0 { + log.Debugf(ctx, "keeping the installed skills %s, which are newer than the compatibility pin %s", installedRef, pin) + return Release{Ref: installedRef}, nil + } + return Release{Ref: pin, Pinned: true}, nil + } + ref, lookupErr := LatestSkillsReleaseRefFn(ctx) + if lookupErr == nil { + return Release{Ref: ref}, nil } if !allowFallback { - return "", false, fmt.Errorf("resolve latest skills release: %w", err) + return Release{}, fmt.Errorf("resolve latest skills release: %w", lookupErr) } - - embedded, embeddedErr := clicompat.ResolveEmbeddedAgentSkillsVersion() - if embeddedErr == nil && embedded != "" && embedded != skillsLatestSentinel { - log.Warnf(ctx, "Could not resolve latest skills release (%v); falling back to embedded skills version %s", err, embedded) - return "v" + embedded, false, nil - } - if embeddedErr != nil { - return "", false, fmt.Errorf("resolve latest skills release: %w (embedded fallback failed: %v)", err, embeddedErr) //nolint:errorlint // only the primary error belongs in the chain + // The embedded manifest is compiled in, so resolving it only fails for a + // broken binary; the other releases still stand. + embedded, _ := clicompat.ResolveEmbeddedAgentSkillsVersion() + fallback := clicompat.NewestRelease(sel.Version, embedded, build.AgentSkillsFallbackVersion(), installedRef) + if fallback == "" { + return Release{}, fmt.Errorf("resolve latest skills release: %w", lookupErr) } - return "", false, fmt.Errorf("resolve latest skills release: %w", err) + log.Debugf(ctx, "could not resolve the latest skills release (%v); using %s", lookupErr, fallback) + return Release{Ref: fallback, LookupErr: lookupErr}, nil } // FetchLatestSkillsReleaseRef returns the skills repo's latest release tag as a -// v-prefixed semver string. A failed request, an unusable response or an invalid -// tag returns a *FetchError with stage release. A request that cannot be built, -// for example from a malformed DATABRICKS_CLI_GITHUB_API_URL, returns a plain +// v-prefixed semver string, read from the version file its release workflow +// publishes. A failed request, an unusable response or an invalid version +// returns a *FetchError with stage release. A request that cannot be built, +// for example from a malformed DATABRICKS_SKILLS_BASE_URL, returns a plain // error instead. func FetchLatestSkillsReleaseRef(ctx context.Context) (string, error) { - url := fmt.Sprintf("%s/repos/%s/%s/releases/latest", versioncheck.GitHubAPIURL(ctx), RepoOwner, RepoName) + url := GetSkillsBaseURL(ctx) + "/" + latestReleasePointer req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) if err != nil { return "", fmt.Errorf("failed to create request: %w", err) @@ -131,26 +160,51 @@ func FetchLatestSkillsReleaseRef(ctx context.Context) (string, error) { } var payload struct { - TagName string `json:"tag_name"` + CurrentVersion string `json:"current_version"` } // A response that arrived but names no usable release is still a failed // release lookup, so these errors carry the stage too. if err := json.NewDecoder(io.LimitReader(resp.Body, MaxFetchBodySize)).Decode(&payload); err != nil { return "", &FetchError{Stage: FetchStageRelease, StatusCode: resp.StatusCode, Err: fmt.Errorf("parse latest skills release: %w", err)} } - tag := strings.TrimSpace(payload.TagName) + tag := strings.TrimSpace(payload.CurrentVersion) if tag == "" { - return "", &FetchError{Stage: FetchStageRelease, StatusCode: resp.StatusCode, Err: errors.New("latest skills release has empty tag_name")} + return "", &FetchError{Stage: FetchStageRelease, StatusCode: resp.StatusCode, Err: errors.New("latest skills release has empty current_version")} } if !strings.HasPrefix(tag, "v") { tag = "v" + tag } if !semver.IsValid(tag) { - return "", &FetchError{Stage: FetchStageRelease, StatusCode: resp.StatusCode, Err: fmt.Errorf("latest skills release has invalid tag %q", payload.TagName)} + return "", &FetchError{Stage: FetchStageRelease, StatusCode: resp.StatusCode, Err: fmt.Errorf("latest skills release has invalid version %q", payload.CurrentVersion)} + } + if err := checkReleasePublished(ctx, tag); err != nil { + return "", err } return tag, nil } +// checkReleasePublished reports, as a failed release lookup, a release whose +// manifest the skills host does not serve. The version file runs ahead of the +// tags while a release is being cut, and stays ahead when its tag push fails, +// so the release it names is used only once its tag exists. +func checkReleasePublished(ctx context.Context, tag string) error { + url := GetSkillsBaseURL(ctx) + "/" + tag + "/" + manifestFile + req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) + if err != nil { + return fmt.Errorf("failed to create request: %w", err) + } + resp, err := HTTPClient().Do(req) + if err != nil { + return &FetchError{Stage: FetchStageRelease, Err: err} + } + defer resp.Body.Close() + _, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, MaxFetchBodySize)) + if resp.StatusCode != http.StatusOK { + return NewHTTPFetchError(FetchStageRelease, resp, fmt.Errorf("latest skills release %s is not published (HTTP %d)", tag, resp.StatusCode)) + } + return nil +} + // GetSkillsBaseURL returns the manifest and skill fetch base URL. // DATABRICKS_SKILLS_BASE_URL overrides GitHub raw URLs for acceptance tests. func GetSkillsBaseURL(ctx context.Context) string { diff --git a/libs/skills/release_source.go b/libs/skills/release_source.go index 71fbfddae17..e15fb1f8c84 100644 --- a/libs/skills/release_source.go +++ b/libs/skills/release_source.go @@ -10,6 +10,8 @@ import ( "net/url" "strings" "time" + + "github.com/databricks/cli/libs/log" ) // releaseTimeout bounds one call to the published release, the release lookup @@ -20,7 +22,7 @@ var releaseTimeout = 5 * time.Second type releaseSource struct{} // NewReleaseSource returns a Source over the published skills release: the -// release GetSkillsRef resolves, read from GetSkillsBaseURL. Each call reads +// release ResolveRelease resolves, read from GetSkillsBaseURL. Each call reads // the release again. A release that cannot be reached, by a timeout, a refused // connection or a server error, fails with ErrSourceUnreachable. func NewReleaseSource() Source { @@ -47,16 +49,19 @@ func (releaseSource) ReadFile(ctx context.Context, skill, file string) ([]byte, return src.ReadFile(ctx, skill, file) } -// openRelease resolves the release ref with GetSkillsRef and returns a Source -// that reads that release's files over HTTP. It does not use the installer's -// embedded-version fallback: a failed lookup is ErrSourceUnreachable, and the -// caller decides what to serve instead. +// openRelease resolves the release with ResolveRelease and returns a Source +// that reads that release's files over HTTP. When the latest release cannot be +// resolved it reads the fallback release; a release that cannot be resolved at +// all is ErrSourceUnreachable, and the caller decides what to serve instead. func openRelease(ctx context.Context) (Source, error) { - ref, _, err := GetSkillsRef(ctx) + rel, err := ResolveRelease(ctx, "", true) if err != nil { return nil, unreachable(err) } - base := GetSkillsBaseURL(ctx) + "/" + ref + if rel.LookupErr != nil { + log.Debugf(ctx, "could not resolve the latest skills release (%v); reading %s", rel.LookupErr, rel.Ref) + } + base := GetSkillsBaseURL(ctx) + "/" + rel.Ref return &fsSource{ read: func(ctx context.Context, name string) ([]byte, error) { // Only the manifest is capped, as the installer caps it. Skill diff --git a/libs/skills/release_source_test.go b/libs/skills/release_source_test.go index 4a80bcf57f1..5b6887a323f 100644 --- a/libs/skills/release_source_test.go +++ b/libs/skills/release_source_test.go @@ -140,7 +140,7 @@ func TestReleaseSourceCallerCancelIsNotUnreachable(t *testing.T) { assert.NotErrorIs(t, err, ErrSourceUnreachable) } -func TestReleaseSourceLatestReleaseLookupFailureIsUnreachable(t *testing.T) { +func TestReleaseSourceUnreachableFallbackAfterFailedLookup(t *testing.T) { prev := releaseTimeout releaseTimeout = 50 * time.Millisecond t.Cleanup(func() { releaseTimeout = prev }) @@ -154,6 +154,11 @@ func TestReleaseSourceLatestReleaseLookupFailureIsUnreachable(t *testing.T) { require.NoError(t, os.WriteFile(filepath.Join(cacheDir, "compat-manifest.json"), []byte(manifest), 0o644)) prevLookup := LatestSkillsReleaseRefFn t.Cleanup(func() { LatestSkillsReleaseRefFn = prevLookup }) + // A failed lookup falls back to a release, read from a server that refuses + // connections here, so the source is unreachable either way. + server := httptest.NewServer(http.NotFoundHandler()) + t.Setenv("DATABRICKS_SKILLS_BASE_URL", server.URL) + server.Close() tests := map[string]func(context.Context) (string, error){ "lookup fails": func(context.Context) (string, error) { @@ -175,6 +180,28 @@ func TestReleaseSourceLatestReleaseLookupFailureIsUnreachable(t *testing.T) { } } +func TestReleaseSourceReadsFallbackWhenLatestLookupFails(t *testing.T) { + // The cached compatibility manifest tracks latest with v1.2.0 as the + // release to fall back to. + t.Setenv("DATABRICKS_SKILLS_REF", "") + cacheDir := t.TempDir() + t.Setenv("DATABRICKS_CACHE_DIR", cacheDir) + manifest := `{"0.0.0": {"appkit": "0.24.0", "skills": "1.2.0", "use_latest": true}}` + require.NoError(t, os.WriteFile(filepath.Join(cacheDir, "compat-manifest.json"), []byte(manifest), 0o644)) + prevLookup := LatestSkillsReleaseRefFn + t.Cleanup(func() { LatestSkillsReleaseRefFn = prevLookup }) + LatestSkillsReleaseRefFn = func(context.Context) (string, error) { + return "", errors.New("HTTP 403") + } + server := httptest.NewServer(http.StripPrefix("/v1.2.0/", http.FileServer(http.FS(os.DirFS("testdata/release"))))) + t.Cleanup(server.Close) + t.Setenv("DATABRICKS_SKILLS_BASE_URL", server.URL) + + catalog, err := NewReleaseSource().Catalog(t.Context()) + require.NoError(t, err) + assert.NotNil(t, catalog) +} + func TestReleaseSourceTimeoutIsUnreachable(t *testing.T) { prev := releaseTimeout releaseTimeout = 50 * time.Millisecond