elelem-skills 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. checksums.yaml +4 -4
  2. data/.agents/backlog/001-enforce-pinned-digests.md +71 -0
  3. data/.agents/backlog/002-refresh-skill-tool-description.md +64 -0
  4. data/.agents/backlog/003-redirect-status-handling.md +47 -0
  5. data/.agents/backlog/004-private-address-fetches.md +58 -0
  6. data/.agents/backlog/005-release-changelog-fixes.md +47 -0
  7. data/.agents/backlog/006-gem-metadata-links.md +65 -0
  8. data/.github/workflows/release.yml +63 -0
  9. data/.release-please-manifest.json +3 -0
  10. data/.rubocop.yml +62 -0
  11. data/CHANGELOG.md +22 -0
  12. data/exe/elelem-skills +6 -0
  13. data/lib/elelem/skills/catalog.rb +7 -10
  14. data/lib/elelem/skills/cli.rb +55 -0
  15. data/lib/elelem/skills/fetcher.rb +90 -16
  16. data/lib/elelem/skills/lockfile.rb +56 -0
  17. data/lib/elelem/skills/setup.rb +27 -10
  18. data/lib/elelem/skills/skill_file.rb +6 -2
  19. data/lib/elelem/skills/version.rb +1 -1
  20. data/lib/elelem/skills.rb +2 -0
  21. data/release-please-config.json +12 -0
  22. data/spec/elelem/skills/catalog_spec.rb +6 -19
  23. data/spec/elelem/skills/cli_spec.rb +66 -0
  24. data/spec/elelem/skills/fetcher_spec.rb +126 -2
  25. data/spec/elelem/skills/lockfile_spec.rb +51 -0
  26. data/spec/elelem/skills/setup_spec.rb +66 -8
  27. data/spec/elelem/skills/skill_file_spec.rb +20 -0
  28. metadata +35 -17
  29. data/lib/elelem/skills/builtin/scrum/SKILL.md +0 -32
  30. data/lib/elelem/skills/builtin/scrum/build.md +0 -29
  31. data/lib/elelem/skills/builtin/scrum/design.md +0 -32
  32. data/lib/elelem/skills/builtin/scrum/plan.md +0 -67
  33. data/lib/elelem/skills/builtin/scrum/review.md +0 -43
  34. data/lib/elelem/skills/builtin/scrum/verify.md +0 -38
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "digest"
4
4
  require "fileutils"
5
+ require "ipaddr"
6
+ require "socket"
5
7
  require "json"
6
8
  require "net/http"
7
9
  require "uri"
@@ -10,26 +12,39 @@ module Elelem
10
12
  module Skills
11
13
  class Fetcher
12
14
  SCHEMA = "https://schemas.agentskills.io/discovery/0.2.0/schema.json"
15
+ MAX_REDIRECTS = 5
16
+ LOCAL_NAMES = %w[localhost].freeze
13
17
 
14
- FetchError = Class.new(StandardError)
18
+ class FetchError < StandardError
19
+ end
15
20
 
16
- def initialize(install_dir: Catalog::REMOTE_SKILLS, http: Net::HTTP)
21
+ def initialize(install_dir: Catalog::REMOTE_SKILLS, http: Net::HTTP, lockfile: nil)
17
22
  @install_dir = install_dir
18
23
  @http = http
24
+ @lockfile = lockfile || Lockfile.new(File.join(install_dir, ".skill-lock.json"))
19
25
  end
20
26
 
21
27
  # Fetches https://<origin>/.well-known/agent-skills/index.json
28
+ # Skills whose pinned digest changed in the last fetch, as "host/name".
29
+ attr_reader :changed
30
+
22
31
  def fetch(origin)
23
32
  base = normalize(origin)
24
- index_url = URI.join(base, "/.well-known/agent-skills/index.json")
25
- index = get_json(index_url)
33
+ @changed = []
34
+ # Only an origin on this machine may lead to this machine.
35
+ @local_origin = local?(base)
36
+ index, index_url = get_json(URI.join(base, "/.well-known/agent-skills/index.json"))
26
37
 
27
38
  unless index["$schema"] == SCHEMA
28
39
  raise FetchError, "unrecognized index schema #{index["$schema"].inspect} at #{index_url} (expected #{SCHEMA})"
29
40
  end
30
41
 
31
- host_dir = File.join(@install_dir, sanitize(base.host))
32
- (index["skills"] || []).filter_map { |entry| install(entry, index_url, host_dir) }
42
+ host = sanitize(base.host)
43
+ # Download and check every skill before writing any, so a bad one
44
+ # leaves nothing half installed.
45
+ downloads = (index["skills"] || []).filter_map { |entry| download(entry, index_url) }
46
+ downloads.each { |skill| install(skill, host) }
47
+ downloads.map { |skill| skill[:name] }
33
48
  end
34
49
 
35
50
  private
@@ -43,22 +58,40 @@ module Elelem
43
58
  host.to_s.downcase.gsub(/[^a-z0-9.-]/, "_")
44
59
  end
45
60
 
46
- def install(entry, index_url, host_dir)
61
+ def download(entry, index_url)
47
62
  name, type, url, digest = entry.values_at("name", "type", "url", "digest")
48
63
 
49
64
  unless type == "skill-md"
50
- Elelem.logger.warn("elelem-skills: fetch: skipping #{name.inspect}, unsupported type #{type.inspect} (archives are not implemented)")
65
+ Elelem.logger.warn("elelem-skills: fetch: skipping #{name.inspect}, unsupported type #{type.inspect} " \
66
+ "(archives are not implemented)")
51
67
  return nil
52
68
  end
69
+ raise FetchError, "#{name.inspect} has no digest, so it cannot be checked" if digest.to_s.empty?
53
70
 
54
- body = get_raw(URI.join(index_url, url))
71
+ skill_url = URI.join(index_url, url)
72
+ body, = get(skill_url)
55
73
  verify!(name, body, digest)
74
+ { name: name, url: skill_url.to_s, digest: digest, body: body }
75
+ end
56
76
 
57
- dir = File.join(host_dir, sanitize(name))
77
+ def install(skill, host)
78
+ warn_if_changed(skill, host)
79
+ dir = File.join(@install_dir, host, sanitize(skill[:name]))
58
80
  FileUtils.mkdir_p(dir)
59
- File.write(File.join(dir, "SKILL.md"), body)
81
+ # Write beside the file, then rename, so a reader never sees half of it.
82
+ tmp = File.join(dir, ".SKILL.md.#{Process.pid}")
83
+ File.binwrite(tmp, skill[:body])
84
+ File.rename(tmp, File.join(dir, "SKILL.md"))
85
+ @lockfile.record(host: host, name: skill[:name], url: skill[:url], digest: skill[:digest])
86
+ end
87
+
88
+ # The first fetch pins a digest. A later, different one is installed, but said out loud.
89
+ def warn_if_changed(skill, host)
90
+ pinned = @lockfile.digest_for(host: host, name: skill[:name])
91
+ return if pinned.nil? || pinned == skill[:digest]
60
92
 
61
- name
93
+ Elelem.logger.warn("elelem-skills: #{host}/#{skill[:name]} changed: was #{pinned}, now #{skill[:digest]}")
94
+ @changed << "#{host}/#{skill[:name]}"
62
95
  end
63
96
 
64
97
  def verify!(name, body, digest)
@@ -69,22 +102,63 @@ module Elelem
69
102
  raise FetchError, "digest mismatch for #{name.inspect}: expected sha256:#{expected}, got sha256:#{actual}"
70
103
  end
71
104
 
105
+ # Returns the parsed body and the URL it came from after any redirects, so
106
+ # relative skill URLs resolve against where the index really is.
72
107
  def get_json(uri)
73
- JSON.parse(get_raw(uri))
108
+ body, final = get(uri)
109
+ [JSON.parse(body), final]
74
110
  rescue JSON::ParserError => e
75
111
  raise FetchError, "invalid JSON at #{uri}: #{e.message}"
76
112
  end
77
113
 
78
- def get_raw(uri)
114
+ def get(uri, hops: MAX_REDIRECTS)
115
+ raise FetchError, "refusing #{uri}: use https" unless secure?(uri)
116
+
79
117
  response = @http.get_response(uri)
118
+ return redirect(uri, response, hops) if response.is_a?(Net::HTTPRedirection)
80
119
  raise FetchError, "GET #{uri} -> #{response.code} #{response.message}" unless response.is_a?(Net::HTTPSuccess)
81
120
 
82
- response.body
121
+ [response.body, uri]
83
122
  rescue FetchError
84
123
  raise
85
- rescue => e
124
+ rescue StandardError => e
86
125
  raise FetchError, "GET #{uri} failed: #{e.class}: #{e.message}"
87
126
  end
127
+
128
+ def redirect(uri, response, hops)
129
+ raise FetchError, "GET #{uri}: too many redirects" if hops.zero?
130
+
131
+ get(URI.join(uri, response["location"].to_s), hops: hops - 1)
132
+ end
133
+
134
+ # This machine, by address rather than spelling: localhost names, and any
135
+ # numeric form the resolver accepts (127.1, 0x7f000001, [0:0::1],
136
+ # ::ffff:127.0.0.1, 0.0.0.0). A DNS name that points at this machine is
137
+ # not caught here; its TLS certificate would have to match.
138
+ def local?(uri)
139
+ name = uri.hostname.to_s.downcase.chomp(".")
140
+ return true if LOCAL_NAMES.include?(name) || name.end_with?(".localhost")
141
+
142
+ numeric_addresses(name).any? { |address| address.loopback? || address.to_i.zero? }
143
+ end
144
+
145
+ def numeric_addresses(name)
146
+ Addrinfo.getaddrinfo(name, nil, nil, :STREAM, nil, Socket::AI_NUMERICHOST).map do |info|
147
+ address = IPAddr.new(info.ip_address)
148
+ address.ipv4_mapped? ? address.native : address
149
+ end
150
+ rescue SocketError
151
+ []
152
+ end
153
+
154
+ # https, or plain http for a skill server on this machine. A remote index
155
+ # cannot redirect to this machine, http or https.
156
+ def secure?(uri)
157
+ local = local?(uri)
158
+ return false if local && !@local_origin
159
+
160
+ uri.scheme == "https" || (uri.scheme == "http" && local)
161
+ end
88
162
  end
89
163
  end
90
164
  end
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require "json"
5
+ require "time"
6
+
7
+ module Elelem
8
+ module Skills
9
+ class Lockfile
10
+ VERSION = 1
11
+
12
+ def initialize(path)
13
+ @path = path
14
+ end
15
+
16
+ def record(host:, name:, url:, digest:)
17
+ data = read
18
+ key = "#{host}/#{name}"
19
+ now = Time.now.utc.iso8601
20
+ installed_at = data.dig("skills", key, "installedAt") || now
21
+
22
+ data["skills"][key] = {
23
+ "host" => host,
24
+ "name" => name,
25
+ "url" => url,
26
+ "digest" => digest,
27
+ "installedAt" => installed_at,
28
+ "updatedAt" => now
29
+ }
30
+
31
+ write(data)
32
+ end
33
+
34
+ def digest_for(host:, name:)
35
+ read.dig("skills", "#{host}/#{name}", "digest")
36
+ end
37
+
38
+ def read
39
+ return { "version" => VERSION, "skills" => {} } unless File.exist?(@path)
40
+
41
+ data = JSON.parse(File.read(@path))
42
+ data["skills"] ||= {}
43
+ data
44
+ rescue JSON::ParserError
45
+ { "version" => VERSION, "skills" => {} }
46
+ end
47
+
48
+ private
49
+
50
+ def write(data)
51
+ FileUtils.mkdir_p(File.dirname(@path))
52
+ File.write(@path, JSON.pretty_generate(data))
53
+ end
54
+ end
55
+ end
56
+ end
@@ -15,8 +15,6 @@ module Elelem
15
15
  end
16
16
 
17
17
  def call
18
- return if @catalog.all.empty?
19
-
20
18
  register_tool
21
19
  register_command
22
20
  end
@@ -27,10 +25,10 @@ module Elelem
27
25
  catalog = @catalog
28
26
 
29
27
  @agent.toolbox.add("skill",
30
- description: "Load a skill's instructions by name. Available skills:\n#{catalog.index(limit: SUMMARY_LIMIT)}",
31
- params: { name: { type: "string", description: "the skill name" } },
32
- required: ["name"]
33
- ) do |a|
28
+ description: "Load a skill's instructions by name. Available skills:\n" \
29
+ "#{catalog.index(limit: SUMMARY_LIMIT)}",
30
+ params: { name: { type: "string", description: "the skill name" } },
31
+ required: ["name"]) do |a|
34
32
  skill = catalog.find(a["name"])
35
33
  next { error: "unknown skill: #{a["name"]}" } unless skill
36
34
 
@@ -43,14 +41,20 @@ module Elelem
43
41
  agent = @agent
44
42
  completions = -> { catalog.all.map(&:name) }
45
43
 
46
- agent.commands.register("skills", description: "List available skills, or `/skills fetch <origin>` to install from a remote index", completions: completions) do |arg|
44
+ agent.commands.register("skills",
45
+ description: "List available skills, or `/skills fetch <origin>` to install " \
46
+ "from a remote index",
47
+ completions: completions) do |arg|
47
48
  if arg&.start_with?("fetch ")
48
49
  fetch(agent, arg.delete_prefix("fetch ").strip)
49
50
  elsif arg && !arg.empty?
50
51
  skill = catalog.find(arg)
51
52
  skill ? agent.output.say(skill.body) : agent.output.say("Unknown skill: #{arg}")
52
53
  else
53
- agent.output.say(catalog.index)
54
+ list = catalog.all.map do |skill|
55
+ "- **#{skill.name}**: #{truncate(skill.description, SUMMARY_LIMIT)}"
56
+ end.join("\n")
57
+ agent.output.say(list.empty? ? "No skills found." : list, as: :markdown)
54
58
  end
55
59
  end
56
60
  end
@@ -61,11 +65,24 @@ module Elelem
61
65
  return
62
66
  end
63
67
 
64
- names = Fetcher.new.fetch(origin)
65
- agent.output.say(names.empty? ? "No skills installed from #{origin}." : "Installed: #{names.join(", ")}\nRestart elelem to pick them up (/reload does not currently re-register this gem's tool -- see README).")
68
+ fetcher = Fetcher.new
69
+ names = fetcher.fetch(origin)
70
+ return agent.output.say("No skills installed from #{origin}.") if names.empty?
71
+
72
+ agent.output.say("Changed since the last fetch: #{fetcher.changed.join(", ")}") if fetcher.changed.any?
73
+
74
+ @catalog.all(reload: true)
75
+ agent.output.say("Installed: #{names.join(", ")}\nAvailable via /skills and the skill tool now. " \
76
+ "Restart elelem to refresh the skill tool's description with the new catalog.")
66
77
  rescue Fetcher::FetchError => e
67
78
  agent.output.say(e.message, as: :error)
68
79
  end
80
+
81
+ def truncate(text, limit)
82
+ return text if text.length <= limit
83
+
84
+ "#{text[0, limit]}..."
85
+ end
69
86
  end
70
87
  end
71
88
  end
@@ -4,10 +4,13 @@ module Elelem
4
4
  module Skills
5
5
  module SkillFile
6
6
  def self.load(path)
7
- parse(File.read(path), path: path)
7
+ # UTF-8 whatever the locale, with any byte order mark dropped.
8
+ parse(File.read(path, encoding: "bom|utf-8"), path: path)
8
9
  end
9
10
 
10
11
  def self.parse(text, path:)
12
+ # Files saved on Windows start with a BOM and end lines with \r\n.
13
+ text = text.delete_prefix("\uFEFF").gsub("\r\n", "\n")
11
14
  frontmatter, body = split(text)
12
15
  unless frontmatter
13
16
  Elelem.logger.warn("elelem-skills: #{path} has no frontmatter, skipping")
@@ -15,7 +18,8 @@ module Elelem
15
18
  end
16
19
 
17
20
  attrs = YAML.safe_load(frontmatter)
18
- name, description = attrs["name"], attrs["description"]
21
+ name = attrs["name"]
22
+ description = attrs["description"]
19
23
  unless name && description
20
24
  Elelem.logger.warn("elelem-skills: #{path} is missing name or description, skipping")
21
25
  return nil
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Elelem
4
4
  module Skills
5
- VERSION = "0.3.0"
5
+ VERSION = "0.4.0"
6
6
  end
7
7
  end
data/lib/elelem/skills.rb CHANGED
@@ -7,8 +7,10 @@ require_relative "skills/version"
7
7
  require_relative "skills/skill"
8
8
  require_relative "skills/skill_file"
9
9
  require_relative "skills/catalog"
10
+ require_relative "skills/lockfile"
10
11
  require_relative "skills/fetcher"
11
12
  require_relative "skills/setup"
13
+ require_relative "skills/cli"
12
14
 
13
15
  Elelem.configure do |config|
14
16
  config.setup(:skills) do |agent|
@@ -0,0 +1,12 @@
1
+ {
2
+ "bootstrap-sha": "c09ebbd8b832c0417d8d108435f8506996476483",
3
+ "packages": {
4
+ ".": {
5
+ "release-type": "ruby",
6
+ "package-name": "elelem-skills",
7
+ "version-file": "lib/elelem/skills/version.rb",
8
+ "bump-minor-pre-major": true,
9
+ "include-component-in-tag": false
10
+ }
11
+ }
12
+ }
@@ -35,20 +35,6 @@ RSpec.describe Elelem::Skills::Catalog do
35
35
  end
36
36
  end
37
37
 
38
- describe "GEM_SKILLS" do
39
- it "bundles the scrum skill with the gem" do
40
- catalog = described_class.new
41
-
42
- expect(catalog.all.map(&:name)).to include("scrum")
43
- end
44
-
45
- it "does not treat the scrum skill's phase files as separate skills" do
46
- catalog = described_class.new
47
-
48
- expect(catalog.all.map(&:name)).not_to include("plan", "design", "build", "review", "verify")
49
- end
50
- end
51
-
52
38
  describe "REMOTE_SKILLS" do
53
39
  it "discovers skills fetched into <remote_skills>/<host>/<name>/SKILL.md" do
54
40
  Dir.mktmpdir do |remote_root|
@@ -62,7 +48,7 @@ RSpec.describe Elelem::Skills::Catalog do
62
48
  body
63
49
  SKILL
64
50
 
65
- catalog = described_class.new(load_paths: [described_class::GEM_SKILLS], remote_skills: remote_root)
51
+ catalog = described_class.new(load_paths: [], remote_skills: remote_root)
66
52
 
67
53
  expect(catalog.find("wrangler")&.description).to eq("fetched from example.com")
68
54
  end
@@ -80,7 +66,7 @@ RSpec.describe Elelem::Skills::Catalog do
80
66
  body
81
67
  SKILL
82
68
 
83
- catalog = described_class.new(load_paths: [described_class::GEM_SKILLS], remote_skills: remote_root)
69
+ catalog = described_class.new(load_paths: [], remote_skills: remote_root)
84
70
 
85
71
  expect(catalog.find("nested-imposter")).to be_nil
86
72
  end
@@ -98,14 +84,15 @@ RSpec.describe Elelem::Skills::Catalog do
98
84
  body
99
85
  SKILL
100
86
 
101
- catalog = described_class.new(load_paths: [described_class::GEM_SKILLS, fixtures], remote_skills: remote_root)
87
+ catalog = described_class.new(load_paths: [fixtures], remote_skills: remote_root)
102
88
 
103
- expect(catalog.find("tdd").description).to eq("Test-driven development. Use when the user wants tests written first.")
89
+ expect(catalog.find("tdd").description)
90
+ .to eq("Test-driven development. Use when the user wants tests written first.")
104
91
  end
105
92
  end
106
93
 
107
94
  it "is not scanned when remote_skills is nil" do
108
- catalog = described_class.new(load_paths: [described_class::GEM_SKILLS], remote_skills: nil)
95
+ catalog = described_class.new(load_paths: [], remote_skills: nil)
109
96
 
110
97
  expect { catalog.all }.not_to raise_error
111
98
  end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec.describe Elelem::Skills::CLI do
4
+ def capture_stdout
5
+ original = $stdout
6
+ $stdout = StringIO.new
7
+ yield
8
+ $stdout.string
9
+ ensure
10
+ $stdout = original
11
+ end
12
+
13
+ describe "#run" do
14
+ it "fetches skills from an origin and prints the installed names" do
15
+ fetcher = instance_double(Elelem::Skills::Fetcher, fetch: ["example"])
16
+ allow(Elelem::Skills::Fetcher).to receive(:new).and_return(fetcher)
17
+
18
+ output = capture_stdout { described_class.new(["fetch", "example.com"]).run }
19
+
20
+ expect(fetcher).to have_received(:fetch).with("example.com")
21
+ expect(output).to include("Installed: example")
22
+ end
23
+
24
+ it "reports when nothing was installed" do
25
+ fetcher = instance_double(Elelem::Skills::Fetcher, fetch: [])
26
+ allow(Elelem::Skills::Fetcher).to receive(:new).and_return(fetcher)
27
+
28
+ output = capture_stdout { described_class.new(["fetch", "example.com"]).run }
29
+
30
+ expect(output).to include("No skills installed from example.com")
31
+ end
32
+
33
+ it "aborts with the fetch error message on failure" do
34
+ fetcher = instance_double(Elelem::Skills::Fetcher)
35
+ allow(fetcher).to receive(:fetch).and_raise(Elelem::Skills::Fetcher::FetchError, "boom")
36
+ allow(Elelem::Skills::Fetcher).to receive(:new).and_return(fetcher)
37
+
38
+ expect { described_class.new(["fetch", "example.com"]).run }.to raise_error(SystemExit)
39
+ end
40
+
41
+ it "requires an origin for fetch" do
42
+ expect { described_class.new(["fetch"]).run }.to raise_error(SystemExit)
43
+ end
44
+
45
+ it "lists discovered skills" do
46
+ fixtures = File.expand_path("../../fixtures/skills", __dir__)
47
+ catalog = instance_double(Elelem::Skills::Catalog,
48
+ all: [Elelem::Skills::Skill.new("tdd", "Test-driven development.", fixtures, "body")])
49
+ allow(Elelem::Skills::Catalog).to receive(:new).and_return(catalog)
50
+
51
+ output = capture_stdout { described_class.new(["list"]).run }
52
+
53
+ expect(output).to include("tdd: Test-driven development.")
54
+ end
55
+
56
+ it "prints usage for an unknown command" do
57
+ expect { described_class.new(["bogus"]).run }.to raise_error(SystemExit)
58
+ end
59
+
60
+ it "prints usage with no args" do
61
+ output = capture_stdout { described_class.new([]).run }
62
+
63
+ expect(output).to include("Usage: elelem-skills")
64
+ end
65
+ end
66
+ end
@@ -3,6 +3,7 @@
3
3
  RSpec.describe Elelem::Skills::Fetcher do
4
4
  let(:install_dir) { Dir.mktmpdir }
5
5
  let(:http) { class_double(Net::HTTP) }
6
+ let(:lockfile) { Elelem::Skills::Lockfile.new(File.join(install_dir, ".skill-lock.json")) }
6
7
  let(:fetcher) { described_class.new(install_dir: install_dir, http: http) }
7
8
 
8
9
  after { FileUtils.rm_rf(install_dir) }
@@ -14,6 +15,13 @@ RSpec.describe Elelem::Skills::Fetcher do
14
15
  res
15
16
  end
16
17
 
18
+ def moved(location)
19
+ res = Net::HTTPMovedPermanently.new("1.1", "301", "Moved Permanently")
20
+ res.instance_variable_set(:@read, true)
21
+ res["location"] = location
22
+ res
23
+ end
24
+
17
25
  def not_found
18
26
  res = Net::HTTPNotFound.new("1.1", "404", "Not Found")
19
27
  res.instance_variable_set(:@read, true)
@@ -34,6 +42,100 @@ RSpec.describe Elelem::Skills::Fetcher do
34
42
  }.to_json
35
43
  end
36
44
 
45
+ describe "#fetch, trust" do
46
+ def two_skill_index(second_digest)
47
+ second = { "name" => "second", "type" => "skill-md", "description" => "Second.",
48
+ "url" => "/.well-known/agent-skills/second/SKILL.md", "digest" => second_digest }
49
+ JSON.parse(index).tap { |i| i["skills"] << second }.to_json
50
+ end
51
+
52
+ def serve(index_body, second_body: skill_body)
53
+ allow(http).to receive(:get_response)
54
+ .with(URI("https://example.com/.well-known/agent-skills/index.json")).and_return(ok(index_body))
55
+ allow(http).to receive(:get_response)
56
+ .with(URI("https://example.com/.well-known/agent-skills/example/SKILL.md")).and_return(ok(skill_body))
57
+ allow(http).to receive(:get_response)
58
+ .with(URI("https://example.com/.well-known/agent-skills/second/SKILL.md")).and_return(ok(second_body))
59
+ end
60
+
61
+ it "refuses a plain http origin" do
62
+ expect { fetcher.fetch("http://example.com") }.to raise_error(described_class::FetchError, /use https/)
63
+ end
64
+
65
+ it "does not let a remote index redirect to this machine, however it is spelled" do
66
+ %w[http://127.0.0.1:8080/x https://[0:0::1]:8443/x https://127.0.0.2/x https://LOCALHOST./x
67
+ https://[::ffff:127.0.0.1]/x https://0.0.0.0/x https://127.1/x https://0x7f000001/x
68
+ https://2130706433/x].each do |target|
69
+ allow(http).to receive(:get_response).and_return(moved(target))
70
+
71
+ expect { fetcher.fetch("example.com") }.to raise_error(described_class::FetchError, /use https/), target
72
+ end
73
+ end
74
+
75
+ it "allows plain http on this machine, for testing" do
76
+ allow(http).to receive(:get_response).and_return(not_found)
77
+
78
+ expect { fetcher.fetch("http://localhost:8080") }.to raise_error(described_class::FetchError, /404/)
79
+ end
80
+
81
+ it "installs nothing when one skill fails its digest" do
82
+ serve(two_skill_index("sha256:#{"0" * 64}"))
83
+
84
+ expect { fetcher.fetch("example.com") }.to raise_error(described_class::FetchError, /digest mismatch/)
85
+ expect(File).not_to exist(File.join(install_dir, "example.com", "example", "SKILL.md"))
86
+ end
87
+
88
+ it "refuses a skill with no digest" do
89
+ serve(index.sub(/"digest":"[^"]*"/, '"digest":null'))
90
+
91
+ expect { fetcher.fetch("example.com") }.to raise_error(described_class::FetchError, /no digest/)
92
+ end
93
+
94
+ it "warns when a pinned digest changes, then installs the new skill" do
95
+ serve(index)
96
+ fetcher.fetch("example.com")
97
+ changed = "---\nname: example\ndescription: Changed.\n---\nNew.\n"
98
+ changed_index = index.sub(digest, "sha256:#{Digest::SHA256.hexdigest(changed)}")
99
+ allow(http).to receive(:get_response)
100
+ .with(URI("https://example.com/.well-known/agent-skills/index.json")).and_return(ok(changed_index))
101
+ allow(http).to receive(:get_response)
102
+ .with(URI("https://example.com/.well-known/agent-skills/example/SKILL.md")).and_return(ok(changed))
103
+ allow(Elelem.logger).to receive(:warn)
104
+
105
+ fetcher.fetch("example.com")
106
+
107
+ expect(Elelem.logger).to have_received(:warn).with(%r{example.com/example changed: was #{digest}})
108
+ expect(fetcher.changed).to eq(["example.com/example"])
109
+ expect(File.read(File.join(install_dir, "example.com", "example", "SKILL.md"))).to eq(changed)
110
+ end
111
+ end
112
+
113
+ describe "#fetch with redirects" do
114
+ it "follows them, and resolves skill URLs against the final index URL" do
115
+ allow(http).to receive(:get_response)
116
+ .with(URI("https://example.com/.well-known/agent-skills/index.json"))
117
+ .and_return(moved("https://www.example.com/.well-known/agent-skills/index.json"))
118
+ allow(http).to receive(:get_response)
119
+ .with(URI("https://www.example.com/.well-known/agent-skills/index.json")).and_return(ok(index))
120
+ allow(http).to receive(:get_response)
121
+ .with(URI("https://www.example.com/.well-known/agent-skills/example/SKILL.md")).and_return(ok(skill_body))
122
+
123
+ expect(fetcher.fetch("example.com")).to eq(["example"])
124
+ end
125
+
126
+ it "refuses a redirect from https to http" do
127
+ allow(http).to receive(:get_response).and_return(moved("http://example.com/index.json"))
128
+
129
+ expect { fetcher.fetch("example.com") }.to raise_error(described_class::FetchError, /use https/)
130
+ end
131
+
132
+ it "stops after too many redirects" do
133
+ allow(http).to receive(:get_response).and_return(moved("/again"))
134
+
135
+ expect { fetcher.fetch("example.com") }.to raise_error(described_class::FetchError, /too many redirects/)
136
+ end
137
+ end
138
+
37
139
  describe "#fetch" do
38
140
  it "installs a skill-md entry whose digest matches" do
39
141
  expect(http).to receive(:get_response)
@@ -49,6 +151,24 @@ RSpec.describe Elelem::Skills::Fetcher do
49
151
  expect(File.read(File.join(install_dir, "example.com", "example", "SKILL.md"))).to eq(skill_body)
50
152
  end
51
153
 
154
+ it "records the install in the lockfile, keyed by host/name" do
155
+ allow(http).to receive(:get_response)
156
+ .with(URI("https://example.com/.well-known/agent-skills/index.json"))
157
+ .and_return(ok(index))
158
+ allow(http).to receive(:get_response)
159
+ .with(URI("https://example.com/.well-known/agent-skills/example/SKILL.md"))
160
+ .and_return(ok(skill_body))
161
+
162
+ fetcher.fetch("example.com")
163
+ entry = lockfile.read.dig("skills", "example.com/example")
164
+
165
+ expect(entry["host"]).to eq("example.com")
166
+ expect(entry["name"]).to eq("example")
167
+ expect(entry["url"]).to eq("https://example.com/.well-known/agent-skills/example/SKILL.md")
168
+ expect(entry["digest"]).to eq(digest)
169
+ expect(entry["installedAt"]).not_to be_nil
170
+ end
171
+
52
172
  it "adds https:// when the origin has no scheme" do
53
173
  expect(http).to receive(:get_response)
54
174
  .with(URI("https://example.com/.well-known/agent-skills/index.json"))
@@ -76,7 +196,9 @@ RSpec.describe Elelem::Skills::Fetcher do
76
196
  .with(URI("https://example.com/.well-known/agent-skills/index.json"))
77
197
  .and_return(ok(bad))
78
198
 
79
- expect { fetcher.fetch("example.com") }.to raise_error(Elelem::Skills::Fetcher::FetchError, /unrecognized index schema/)
199
+ expect do
200
+ fetcher.fetch("example.com")
201
+ end.to raise_error(Elelem::Skills::Fetcher::FetchError, /unrecognized index schema/)
80
202
  end
81
203
 
82
204
  it "raises when the schema field is absent (treated as incompatible v0.1.0)" do
@@ -85,7 +207,9 @@ RSpec.describe Elelem::Skills::Fetcher do
85
207
  .with(URI("https://example.com/.well-known/agent-skills/index.json"))
86
208
  .and_return(ok(no_schema))
87
209
 
88
- expect { fetcher.fetch("example.com") }.to raise_error(Elelem::Skills::Fetcher::FetchError, /unrecognized index schema/)
210
+ expect do
211
+ fetcher.fetch("example.com")
212
+ end.to raise_error(Elelem::Skills::Fetcher::FetchError, /unrecognized index schema/)
89
213
  end
90
214
 
91
215
  it "skips archive entries and warns, without raising" do