diff --git a/Sources/CLI/cmd/agent/skills/AgentSkillsCommand.swift b/Sources/CLI/cmd/agent/skills/AgentSkillsCommand.swift index ad093df..213ca3d 100644 --- a/Sources/CLI/cmd/agent/skills/AgentSkillsCommand.swift +++ b/Sources/CLI/cmd/agent/skills/AgentSkillsCommand.swift @@ -10,6 +10,7 @@ struct AgentSkillsCommand: ParsableCommand, GlobalOptionsProviding { AgentSkillsListCommand.self, AgentSkillsGetCommand.self, AgentSkillsInstallCommand.self, + AgentSkillsUpdateCommand.self, AgentSkillsUninstallCommand.self, ] ) diff --git a/Sources/CLI/cmd/agent/skills/AgentSkillsInstallCommand.swift b/Sources/CLI/cmd/agent/skills/AgentSkillsInstallCommand.swift index 37b9bd2..6084684 100644 --- a/Sources/CLI/cmd/agent/skills/AgentSkillsInstallCommand.swift +++ b/Sources/CLI/cmd/agent/skills/AgentSkillsInstallCommand.swift @@ -41,7 +41,8 @@ struct AgentSkillsInstallCommand: ParsableCommand, GlobalOptionsProviding { func run(deps: Deps) throws { do { let outcomes = try deps.agentSkillInstallationService().install( - selection.selectedSkills(), root: selection.installationRoot(fileManager: deps.agentSkillFileManager()), + selection.selectedSkills(), + root: selection.root.installationRoot(fileManager: deps.agentSkillFileManager()), dryRun: selection.dryRun, force: force ) deps.commandOutputWriter.write(AgentSkillInstallationRenderer().render(outcomes)) diff --git a/Sources/CLI/cmd/agent/skills/AgentSkillsListCommand.swift b/Sources/CLI/cmd/agent/skills/AgentSkillsListCommand.swift index 6e276cf..e89a9ba 100644 --- a/Sources/CLI/cmd/agent/skills/AgentSkillsListCommand.swift +++ b/Sources/CLI/cmd/agent/skills/AgentSkillsListCommand.swift @@ -2,26 +2,33 @@ import ArgumentParser struct AgentSkillsListCommand: ParsableCommand, GlobalOptionsProviding { #if DEBUG - typealias Deps = any (TelemetryProvider & CommandOutputWriterProvider) + typealias Deps = any (TelemetryProvider & CommandOutputWriterProvider & AgentSkillInstallationServiceProvider) #else typealias Deps = Dependencies #endif @OptionGroup var global: GlobalOptions + @OptionGroup var root: AgentSkillsRootOptions static let configuration = CommandConfiguration( commandName: "list", - abstract: "List Agent Skills bundled with apple-docs." + abstract: "List bundled Agent Skills with installation status and paths." ) mutating func run() throws { - run(deps: AppleDocs.dependencies) + try run(deps: AppleDocs.dependencies) } - func run(deps: Deps) { + func run(deps: Deps) throws { deps.telemetry.startCommand(.agentSkillsList) - for skill in BundledAgentSkills.all { - deps.commandOutputWriter.write("\(skill.name)\t\(skill.shortDescription)") + do { + let installations = try deps.agentSkillInstallationService().list( + BundledAgentSkills.all, root: root.installationRoot(fileManager: deps.agentSkillFileManager())) + for line in AgentSkillInstallationRenderer().renderList(installations) { + deps.commandOutputWriter.write(line) + } + } catch let error as AgentSkillInstallationError { + throw ValidationError(error.localizedDescription) } } } diff --git a/Sources/CLI/cmd/agent/skills/AgentSkillsSelectionOptions.swift b/Sources/CLI/cmd/agent/skills/AgentSkillsSelectionOptions.swift index 0e86c33..c8dc941 100644 --- a/Sources/CLI/cmd/agent/skills/AgentSkillsSelectionOptions.swift +++ b/Sources/CLI/cmd/agent/skills/AgentSkillsSelectionOptions.swift @@ -8,21 +8,14 @@ struct AgentSkillsSelectionOptions: ParsableArguments { @Flag(help: "Select all bundled skills. Cannot be combined with skill names.") var all = false - @Option(help: "Root of the .agents installation. Skills are stored under DIR/skills.") - var dir: String? - - @Flag( - help: "Use the Git root's .agents directory (current directory outside Git). Conflicts with --dir." - ) - var project = false + @OptionGroup var root: AgentSkillsRootOptions @Flag(help: "Preview changes without writing or removing files.") var dryRun = false - func selectedSkills() throws -> [BundledAgentSkill] { - if project, dir != nil { - throw ValidationError("Use either --project or --dir, not both.") - } + func selectedSkills(defaultToAll: Bool = false) throws -> [BundledAgentSkill] { + try root.validate() + if defaultToAll, !all, skills.isEmpty { return BundledAgentSkills.all } guard all != !skills.isEmpty else { throw ValidationError("Specify one or more skill names, or --all, but not both.") } @@ -36,6 +29,21 @@ struct AgentSkillsSelectionOptions: ParsableArguments { } } +} + +struct AgentSkillsRootOptions: ParsableArguments { + @Option(help: "Root of the .agents installation. Skills are stored under DIR/skills.") + var dir: String? + + @Flag(help: "Use the Git root's .agents directory (current directory outside Git). Conflicts with --dir.") + var project = false + + func validate() throws { + if project, dir != nil { + throw ValidationError("Use either --project or --dir, not both.") + } + } + func installationRoot(fileManager: AgentSkillFileSystem) -> String { if project { let currentDirectory = URL(fileURLWithPath: fileManager.currentDirectoryPath).standardizedFileURL diff --git a/Sources/CLI/cmd/agent/skills/AgentSkillsUninstallCommand.swift b/Sources/CLI/cmd/agent/skills/AgentSkillsUninstallCommand.swift index 2054f71..40f4e53 100644 --- a/Sources/CLI/cmd/agent/skills/AgentSkillsUninstallCommand.swift +++ b/Sources/CLI/cmd/agent/skills/AgentSkillsUninstallCommand.swift @@ -44,7 +44,8 @@ struct AgentSkillsUninstallCommand: ParsableCommand, GlobalOptionsProviding { func run(deps: Deps) throws { do { let outcomes = try deps.agentSkillInstallationService().uninstall( - selection.selectedSkills(), root: selection.installationRoot(fileManager: deps.agentSkillFileManager()), + selection.selectedSkills(), + root: selection.root.installationRoot(fileManager: deps.agentSkillFileManager()), dryRun: selection.dryRun ) deps.commandOutputWriter.write(AgentSkillInstallationRenderer().render(outcomes)) diff --git a/Sources/CLI/cmd/agent/skills/AgentSkillsUpdateCommand.swift b/Sources/CLI/cmd/agent/skills/AgentSkillsUpdateCommand.swift new file mode 100644 index 0000000..7ec2a9b --- /dev/null +++ b/Sources/CLI/cmd/agent/skills/AgentSkillsUpdateCommand.swift @@ -0,0 +1,55 @@ +import ArgumentParser + +struct AgentSkillsUpdateCommand: ParsableCommand, GlobalOptionsProviding { + #if DEBUG + typealias Deps = any (AgentSkillInstallationServiceProvider & CommandOutputWriterProvider) + #else + typealias Deps = Dependencies + #endif + + @OptionGroup var global: GlobalOptions + + static let configuration = CommandConfiguration( + commandName: "update", + abstract: "Update installed skills managed by apple-docs.", + discussion: """ + With no names, updates all managed bundled skills already installed. Does not install missing + or unmanaged skills. Local edits are preserved and must be resolved before updating. + Use --project for the Git root (current directory outside Git), or --dir for another root. + + Examples: + apple-docs agent skills update + apple-docs agent skills update --dry-run + apple-docs agent skills update apple-docs --project + """ + ) + + @OptionGroup var selection: AgentSkillsSelectionOptions + + mutating func validate() throws { + _ = try selection.selectedSkills(defaultToAll: true) + } + + mutating func run() throws { + try run(deps: AppleDocs.dependencies) + } + + func run(deps: Deps) throws { + do { + let outcomes = try deps.agentSkillInstallationService().update( + selection.selectedSkills(defaultToAll: true), + root: selection.root.installationRoot(fileManager: deps.agentSkillFileManager()), + dryRun: selection.dryRun + ) + deps.commandOutputWriter.write(AgentSkillInstallationRenderer().render(outcomes)) + } catch let failure as AgentSkillBatchFailure { + deps.commandOutputWriter.write(AgentSkillInstallationRenderer().render(failure.completed)) + if let error = failure.underlying as? AgentSkillInstallationError { + throw ValidationError(error.localizedDescription) + } + throw failure.underlying + } catch let error as AgentSkillInstallationError { + throw ValidationError(error.localizedDescription) + } + } +} diff --git a/Sources/CLI/main/AgentSkillErrorPresentation.swift b/Sources/CLI/main/AgentSkillErrorPresentation.swift index 1ad75b6..7818e8e 100644 --- a/Sources/CLI/main/AgentSkillErrorPresentation.swift +++ b/Sources/CLI/main/AgentSkillErrorPresentation.swift @@ -9,7 +9,7 @@ extension AgentSkillInstallationError: LocalizedError { case .modifiedSkill(let name, let removing): return removing ? "Skill '\(name)' was edited. Back up and restore it before uninstalling." - : "Skill '\(name)' differs. Use --force to replace the managed file." + : "Skill '\(name)' differs. To replace it, use 'apple-docs agent skills install \(name) --force'." case .invalidReceipt(let url): return "Invalid apple-docs installation receipt at '\(url.path)'." case .invalidDirectory(let url): return "Expected a directory, not a symlink or other file, at '\(url.path)'." diff --git a/Sources/CLI/renderer/AgentSkillInstallationRenderer.swift b/Sources/CLI/renderer/AgentSkillInstallationRenderer.swift index 5f74d8e..96950bb 100644 --- a/Sources/CLI/renderer/AgentSkillInstallationRenderer.swift +++ b/Sources/CLI/renderer/AgentSkillInstallationRenderer.swift @@ -1,12 +1,17 @@ struct AgentSkillInstallationRenderer { func render(_ outcomes: [AgentSkillInstallationOutcome]) -> String { - outcomes.map { outcome in + guard !outcomes.isEmpty else { return "No skills to process." } + let lines = outcomes.map { outcome in let action: String switch outcome.status { - case .installed, .updated: + case .installed: action = "Installed: \(outcome.name) at \(outcome.file.path)" - case .wouldInstall, .wouldUpdate: + case .updated: + action = "Updated: \(outcome.name) at \(outcome.file.path)" + case .wouldInstall: action = "Would install: \(outcome.name) at \(outcome.file.path)" + case .wouldUpdate: + action = "Would update: \(outcome.name) at \(outcome.file.path)" case .unchanged: action = "Unchanged: \(outcome.name)" case .uninstalled: action = "Uninstalled: \(outcome.name)" case .wouldUninstall: action = "Would uninstall: \(outcome.name)" @@ -14,6 +19,24 @@ struct AgentSkillInstallationRenderer { } let recovery = outcome.requiresRecovery ? "Would recover pending operation: \(outcome.name)\n" : "" return recovery + action - }.joined(separator: "\n") + } + let labels: [(AgentSkillInstallationOutcome.Status, String)] = [ + (.installed, "installed"), (.updated, "updated"), (.unchanged, "unchanged"), + (.uninstalled, "uninstalled"), (.notInstalled, "not installed"), + (.wouldInstall, "would install"), (.wouldUpdate, "would update"), (.wouldUninstall, "would uninstall"), + ] + let counts = labels.compactMap { status, label -> String? in + let count = outcomes.filter { $0.status == status }.count + return count == 0 ? nil : "\(count) \(label)" + } + return (lines + ["Summary: " + counts.joined(separator: ", ")]).joined(separator: "\n") + } + + func renderList(_ installations: [AgentSkillInstallationStatus]) -> [String] { + installations.map { installation in + let recovery = installation.requiresRecovery ? " (pending recovery)" : "" + return "\(installation.skill.name)\t\(installation.status.rawValue)\(recovery)\t\(installation.file.path)" + + "\t\(installation.skill.shortDescription)" + } } } diff --git a/Sources/CLI/skills/AgentSkillInstallationOutcome.swift b/Sources/CLI/skills/AgentSkillInstallationOutcome.swift index 43d5cb3..4b9f300 100644 --- a/Sources/CLI/skills/AgentSkillInstallationOutcome.swift +++ b/Sources/CLI/skills/AgentSkillInstallationOutcome.swift @@ -12,6 +12,22 @@ struct AgentSkillInstallationOutcome: Equatable, Sendable { var requiresRecovery = false } +struct AgentSkillInstallationStatus { + enum Status: String { + case installed + case updateAvailable = "update available" + case modified + case unmanaged + case notInstalled = "not installed" + case missing + } + + let skill: BundledAgentSkill + let file: URL + let status: Status + let requiresRecovery: Bool +} + enum AgentSkillInstallationError: Error, Equatable { case emptyRoot case unmanagedSkill(name: String, removing: Bool) diff --git a/Sources/CLI/skills/AgentSkillInstallationService.swift b/Sources/CLI/skills/AgentSkillInstallationService.swift index 2e2b102..26a0a35 100644 --- a/Sources/CLI/skills/AgentSkillInstallationService.swift +++ b/Sources/CLI/skills/AgentSkillInstallationService.swift @@ -61,6 +61,40 @@ struct DefaultAgentSkillInstallationService { } } + func list(_ skills: [BundledAgentSkill], root: String) throws -> [AgentSkillInstallationStatus] { + try inspect(skills, root: root).map { installation in + let status: AgentSkillInstallationStatus.Status + if let content = installation.content { + if let receipt = installation.receipt { + if content != receipt.content { + status = .modified + } else { + status = content == Data(installation.skill.content.utf8) ? .installed : .updateAvailable + } + } else { + status = .unmanaged + } + } else { + status = installation.receipt == nil ? .notInstalled : .missing + } + return AgentSkillInstallationStatus( + skill: installation.skill, file: installation.file, status: status, + requiresRecovery: installation.inspection.pending != nil) + } + } + + func update( + _ skills: [BundledAgentSkill], root: String, dryRun: Bool + ) throws -> [AgentSkillInstallationOutcome] { + let installations = try inspect(skills, root: root).filter { $0.receipt != nil && $0.content != nil } + for installation in installations { + guard installation.content == installation.receipt?.content else { + throw AgentSkillInstallationError.modifiedSkill(name: installation.skill.name, removing: false) + } + } + return try execute(installations) { try install($0, dryRun: dryRun, force: false) } + } + func uninstall( _ skills: [BundledAgentSkill], root: String, dryRun: Bool ) throws -> [AgentSkillInstallationOutcome] { @@ -135,8 +169,12 @@ struct DefaultAgentSkillInstallationService { from: installation.inspection.state, to: .init(content: content, receipt: .init(name: installation.skill.name, content: content))) } - logger.info(dryRun ? "Would install skill" : "Installed skill", metadata: metadata) let updating = installation.content != nil + if updating { + logger.info(dryRun ? "Would update skill" : "Updated skill", metadata: metadata) + } else { + logger.info(dryRun ? "Would install skill" : "Installed skill", metadata: metadata) + } return AgentSkillInstallationOutcome( name: installation.skill.name, file: installation.file, status: dryRun ? (updating ? .wouldUpdate : .wouldInstall) : (updating ? .updated : .installed), @@ -179,6 +217,8 @@ struct DefaultAgentSkillInstallationService { #if DEBUG protocol AgentSkillInstallationService { + func list(_ skills: [BundledAgentSkill], root: String) throws -> [AgentSkillInstallationStatus] + func update(_ skills: [BundledAgentSkill], root: String, dryRun: Bool) throws -> [AgentSkillInstallationOutcome] func install(_ skills: [BundledAgentSkill], root: String, dryRun: Bool, force: Bool) throws -> [AgentSkillInstallationOutcome] func uninstall(_ skills: [BundledAgentSkill], root: String, dryRun: Bool) throws diff --git a/Sources/CLI/skills/BundledAgentSkills.swift b/Sources/CLI/skills/BundledAgentSkills.swift index fe5f0eb..9cb4479 100644 --- a/Sources/CLI/skills/BundledAgentSkills.swift +++ b/Sources/CLI/skills/BundledAgentSkills.swift @@ -142,14 +142,19 @@ extension BundledAgentSkills { apple-docs agent skills get apple-docs-discover-api apple-docs agent skills install --all --dry-run apple-docs agent skills install --all + apple-docs agent skills update --dry-run + apple-docs agent skills update apple-docs agent skills uninstall --all --dry-run apple-docs agent skills uninstall --all --yes ``` - Skills install under `~/.agents/skills`. Use `--dir .agents` for project-local skills, or another .agents root. + Skills install under `~/.agents/skills`. Use `--project` for the Git root (current directory outside Git), + or `--dir` for another .agents root. List reports installation status and paths for the selected root. + Update refreshes only installed managed skills and refuses local edits. Use `--dry-run` to preview changes. Installation does not configure individual agent tools. The tool must support that skill directory convention. - Obtain user approval before installing or removing skills. `--force` replaces differing managed SKILL.md files - only, never unmanaged files. Uninstall refuses modified managed files and preserves unrelated files. + Obtain user approval before installing, updating, or removing skills. `--force` replaces differing managed + SKILL.md files only, never unmanaged files. Uninstall refuses modified managed files and preserves + unrelated files. """ private static let discoverAPIContent = """ diff --git a/Tests/CLITests/cmd/agent/skills/AgentSkillsCommandTests.swift b/Tests/CLITests/cmd/agent/skills/AgentSkillsCommandTests.swift index e24c7dd..6a028da 100644 --- a/Tests/CLITests/cmd/agent/skills/AgentSkillsCommandTests.swift +++ b/Tests/CLITests/cmd/agent/skills/AgentSkillsCommandTests.swift @@ -1,3 +1,5 @@ +import Foundation +import Logging import Testing @testable import CLI @@ -7,11 +9,13 @@ struct AgentSkillsCommandTests { @Test("list writes the bundled skill names through the injected output") func writesSkillList() throws { // -- Arrange -- - let command = try AgentSkillsListCommand.parse([]) + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + let command = try AgentSkillsListCommand.parse(["--dir", root.path]) let deps = SkillListDependencies() // -- Act -- - command.run(deps: deps) + try command.run(deps: deps) // -- Assert -- #expect(deps.output.lines.count == BundledAgentSkills.all.count) @@ -38,6 +42,41 @@ struct AgentSkillsCommandTests { #expect(deps.telemetry.commands == ["agent.skills.get"]) } + @Test("list distinguishes installation state without changing files") + func listsInstallationState() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + let deps = SkillListDependencies() + let service = deps.agentSkillInstallationService() + _ = try service.install(Array(BundledAgentSkills.all.prefix(3)), root: root.path, dryRun: false, force: false) + let outdated = root.appendingPathComponent("skills/apple-docs-discover-api") + try Data("previous version".utf8).write(to: outdated.appendingPathComponent("SKILL.md")) + let receipt = AgentSkillInstallationStore.Receipt( + name: "apple-docs-discover-api", content: Data("previous version".utf8)) + try JSONEncoder().encode(receipt).write(to: outdated.appendingPathComponent(".apple-docs-managed.json")) + let modified = root.appendingPathComponent("skills/apple-docs-check-availability/SKILL.md") + try Data("local edits".utf8).write(to: modified) + let unmanaged = root.appendingPathComponent("skills/apple-docs-support") + try FileManager.default.createDirectory(at: unmanaged, withIntermediateDirectories: true) + try Data("user skill".utf8).write(to: unmanaged.appendingPathComponent("SKILL.md")) + let command = try AgentSkillsListCommand.parse(["--dir", root.path]) + + // -- Act -- + try command.run(deps: deps) + + // -- Assert -- + #expect(deps.output.lines.contains { $0.hasPrefix("apple-docs\tinstalled\t") }) + #expect(deps.output.lines.contains { $0.hasPrefix("apple-docs-discover-api\tupdate available\t") }) + #expect(deps.output.lines.contains { $0.hasPrefix("apple-docs-check-availability\tmodified\t") }) + #expect(deps.output.lines.contains { $0.hasPrefix("apple-docs-support\tunmanaged\t") }) + #expect(deps.output.lines.contains { $0.hasPrefix("apple-docs-terms\tnot installed\t") }) + #expect(deps.output.lines.allSatisfy { $0.contains(root.path) }) + #expect(try String(contentsOf: modified, encoding: .utf8) == "local edits") + #expect( + try String(contentsOf: outdated.appendingPathComponent("SKILL.md"), encoding: .utf8) == "previous version") + } + @Test("registers the nested list command") func parsesListCommand() throws { // -- Arrange -- @@ -62,10 +101,21 @@ struct AgentSkillsCommandTests { let getCommand = try #require(command as? AgentSkillsGetCommand) #expect(getCommand.name == "apple-docs") } + private func temporaryRoot() -> URL { + FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent(UUID().uuidString) + } } private struct SkillListDependencies: TelemetryProvider, CommandOutputWriterProvider { let telemetry = RecordingCommandTelemetry() let output = RecordingCommandOutputWriter() var commandOutputWriter: RecordingCommandOutputWriter { output } + + func agentSkillFileManager() -> FileManager { .default } + + func agentSkillInstallationService() -> DefaultAgentSkillInstallationService { + DefaultAgentSkillInstallationService(logger: Logger(label: "test")) + } } + +extension SkillListDependencies: AgentSkillInstallationServiceProvider {} diff --git a/Tests/CLITests/cmd/agent/skills/AgentSkillsInstallationTests.swift b/Tests/CLITests/cmd/agent/skills/AgentSkillsInstallationTests.swift index 84bf531..6bdaa8f 100644 --- a/Tests/CLITests/cmd/agent/skills/AgentSkillsInstallationTests.swift +++ b/Tests/CLITests/cmd/agent/skills/AgentSkillsInstallationTests.swift @@ -76,7 +76,8 @@ struct AgentSkillsInstallationTests { ["install"], ["install", "--all", "apple-docs"], ["install", "apple-docs", "unknown"], ["install", "../escape"], ["uninstall"], ["uninstall", "--all"], ["uninstall", "--all", "apple-docs", "--yes"], - ["uninstall", "unknown"], + ["uninstall", "unknown"], ["update", "unknown"], ["update", "--all", "apple-docs"], + ["update", "--project"], ["list", "--project"], ]) func rejectsInvalidSelection(arguments: [String]) throws { // -- Arrange -- diff --git a/Tests/CLITests/cmd/agent/skills/AgentSkillsProjectInstallationTests.swift b/Tests/CLITests/cmd/agent/skills/AgentSkillsProjectInstallationTests.swift index 28f1482..7153dda 100644 --- a/Tests/CLITests/cmd/agent/skills/AgentSkillsProjectInstallationTests.swift +++ b/Tests/CLITests/cmd/agent/skills/AgentSkillsProjectInstallationTests.swift @@ -25,6 +25,7 @@ struct AgentSkillsProjectInstallationTests { #expect( deps.output.lines == [ "Installed: apple-docs at \(home.appendingPathComponent(".agents/skills/apple-docs/SKILL.md").path)" + + "\nSummary: 1 installed" ]) } @@ -47,7 +48,7 @@ struct AgentSkillsProjectInstallationTests { #expect( !FileManager.default.fileExists( atPath: home.appendingPathComponent(".agents/skills/apple-docs/SKILL.md").path)) - #expect(deps.output.lines.last == "Uninstalled: apple-docs") + #expect(deps.output.lines.last == "Uninstalled: apple-docs\nSummary: 1 uninstalled") } @Test("project installation targets the Git root from a nested directory") @@ -145,6 +146,38 @@ struct AgentSkillsProjectInstallationTests { #expect(!FileManager.default.fileExists(atPath: home.path)) } + @Test("project list and update share the installation root") + func listsAndUpdatesProjectInstallation() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + let nested = root.appendingPathComponent("src/nested") + try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: root.appendingPathComponent(".git"), withIntermediateDirectories: true) + let deps = TestAgentSkillDependencies(fileManager: TestHomeFileManager(home: root, currentDirectory: nested)) + let service = deps.agentSkillInstallationService() + let previous = BundledAgentSkill(name: "apple-docs", shortDescription: "Fixture", content: "previous version") + let agents = root.appendingPathComponent(".agents") + _ = try service.install([previous], root: agents.path, dryRun: false, force: false) + let list = try AgentSkillsListCommand.parse(["--project"]) + let update = try AgentSkillsUpdateCommand.parse(["--project"]) + + // -- Act -- + try list.run(deps: deps) + let beforeUpdate = deps.output.lines + try update.run(deps: deps) + try list.run(deps: deps) + + // -- Assert -- + #expect(beforeUpdate.first?.hasPrefix("apple-docs\tupdate available\t") == true) + #expect(beforeUpdate.first?.contains(agents.path) == true) + #expect( + deps.output.lines.contains { $0.hasPrefix("Updated: apple-docs at") && $0.hasSuffix("Summary: 1 updated") }) + #expect(deps.output.lines.contains { $0.hasPrefix("apple-docs\tinstalled\t") }) + #expect(!FileManager.default.fileExists(atPath: nested.appendingPathComponent(".agents").path)) + } + @Test("project and dir cannot be combined") func rejectsAmbiguousInstallationRoot() throws { // -- Arrange -- @@ -188,6 +221,7 @@ struct AgentSkillsProjectInstallationTests { } private struct TestAgentSkillDependencies: AgentSkillInstallationServiceProvider, CommandOutputWriterProvider { + let telemetry = RecordingCommandTelemetry() let fileManager: FileManager let output = RecordingCommandOutputWriter() var commandOutputWriter: RecordingCommandOutputWriter { output } @@ -199,6 +233,8 @@ private struct TestAgentSkillDependencies: AgentSkillInstallationServiceProvider } } +extension TestAgentSkillDependencies: TelemetryProvider {} + private final class DenyingInstallationFileManager: FileManager { enum Denied: Error { case createDirectory } diff --git a/Tests/CLITests/cmd/agent/skills/AgentSkillsUpdateTests.swift b/Tests/CLITests/cmd/agent/skills/AgentSkillsUpdateTests.swift new file mode 100644 index 0000000..a18b301 --- /dev/null +++ b/Tests/CLITests/cmd/agent/skills/AgentSkillsUpdateTests.swift @@ -0,0 +1,137 @@ +import Foundation +import Testing + +@testable import CLI + +@Suite("Agent skills updates") +struct AgentSkillsUpdateTests { + @Test("update refreshes only managed installations and leaves uninstalled skills absent") + func updatesInstalledSkills() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + try installPreviousVersion(at: root) + let unmanaged = skillFile(root, name: "apple-docs-support") + try write("user skill", to: unmanaged) + + // -- Act -- + try run(["update", "--dir", root.path]) + try run(["update", "--dir", root.path]) + + // -- Assert -- + #expect(try String(contentsOf: skillFile(root), encoding: .utf8) == BundledAgentSkills.all[0].content) + #expect(try String(contentsOf: unmanaged, encoding: .utf8) == "user skill") + #expect(!FileManager.default.fileExists(atPath: skillFile(root, name: "apple-docs-terms").path)) + } + + @Test("update dry run preserves the previous version") + func previewsUpdate() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + try installPreviousVersion(at: root) + + // -- Act -- + try run(["update", "--dry-run", "--dir", root.path]) + + // -- Assert -- + #expect(try String(contentsOf: skillFile(root), encoding: .utf8) == "previous version") + } + + @Test("update without installations does not create a root") + func updatesEmptyInstallation() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + + // -- Act -- + try run(["update", "--dir", root.path]) + + // -- Assert -- + #expect(!FileManager.default.fileExists(atPath: root.path)) + } + + @Test("update leaves missing managed files absent") + func skipsMissingManagedFiles() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + try installPreviousVersion(at: root) + try FileManager.default.removeItem(at: skillFile(root)) + + // -- Act -- + try run(["update", "--dir", root.path]) + + // -- Assert -- + #expect(!FileManager.default.fileExists(atPath: skillFile(root).path)) + #expect( + FileManager.default.fileExists( + atPath: root.appendingPathComponent("skills/apple-docs/.apple-docs-managed.json").path)) + } + + @Test("named updates do not update other installed skills") + func updatesNamedSkills() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + try installPreviousVersion(at: root) + try installPreviousVersion(at: root, name: "apple-docs-support") + + // -- Act -- + try run(["update", "apple-docs", "apple-docs", "--dir", root.path]) + + // -- Assert -- + #expect(try String(contentsOf: skillFile(root), encoding: .utf8) == BundledAgentSkills.all[0].content) + #expect( + try String(contentsOf: skillFile(root, name: "apple-docs-support"), encoding: .utf8) == "previous version") + } + + @Test("update preflights local edits before changing any installed skill") + func protectsEditsDuringUpdate() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + try installPreviousVersion(at: root) + try installPreviousVersion(at: root, name: "apple-docs-support") + let edited = skillFile(root, name: "apple-docs-support") + try write("local edits", to: edited) + + // -- Act -- + do { + try run(["update", "--dir", root.path]) + Issue.record("Expected update to refuse local edits") + } catch { + #expect(CLI.message(for: error).contains("install apple-docs-support --force")) + } + + // -- Assert -- + #expect(try String(contentsOf: skillFile(root), encoding: .utf8) == "previous version") + #expect(try String(contentsOf: edited, encoding: .utf8) == "local edits") + } + + private func installPreviousVersion(at root: URL, name: String = "apple-docs") throws { + try write("previous version", to: skillFile(root, name: name)) + let receipt = AgentSkillInstallationStore.Receipt(name: name, content: Data("previous version".utf8)) + try JSONEncoder().encode(receipt).write( + to: root.appendingPathComponent("skills/\(name)/.apple-docs-managed.json")) + } + + private func run(_ arguments: [String]) throws { + var command = try CLI.parseAsRoot(["agent", "skills"] + arguments) + try command.run() + } + + private func temporaryRoot() -> URL { + FileManager.default.temporaryDirectory.resolvingSymlinksInPath() + .appendingPathComponent(UUID().uuidString) + } + + private func skillFile(_ root: URL, name: String = "apple-docs") -> URL { + root.appendingPathComponent("skills/\(name)/SKILL.md") + } + + private func write(_ content: String, to url: URL) throws { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(content.utf8).write(to: url) + } +} diff --git a/Tests/CLITests/renderer/AgentSkillInstallationRendererTests.swift b/Tests/CLITests/renderer/AgentSkillInstallationRendererTests.swift new file mode 100644 index 0000000..3d976fd --- /dev/null +++ b/Tests/CLITests/renderer/AgentSkillInstallationRendererTests.swift @@ -0,0 +1,57 @@ +import Foundation +import Testing + +@testable import CLI + +@Suite("Skill installation reporting") +struct AgentSkillInstallationRendererTests { + @Test("distinguishes updates from new installations and summarizes outcomes") + func reportsInstallAndUpdate() { + // -- Arrange -- + let file = URL(fileURLWithPath: "/tmp/skills/example/SKILL.md") + let outcomes = [ + AgentSkillInstallationOutcome(name: "new", file: file, status: .installed), + AgentSkillInstallationOutcome(name: "old", file: file, status: .updated), + AgentSkillInstallationOutcome(name: "current", file: file, status: .unchanged), + ] + + // -- Act -- + let output = AgentSkillInstallationRenderer().render(outcomes) + + // -- Assert -- + #expect(output.contains("Installed: new at")) + #expect(output.contains("Updated: old at")) + #expect(output.contains("Unchanged: current")) + #expect(output.hasSuffix("Summary: 1 installed, 1 updated, 1 unchanged")) + } + + @Test("reports preview counts without claiming changes were made") + func reportsPreview() { + // -- Arrange -- + let file = URL(fileURLWithPath: "/tmp/skills/example/SKILL.md") + let outcomes = [ + AgentSkillInstallationOutcome(name: "new", file: file, status: .wouldInstall), + AgentSkillInstallationOutcome(name: "old", file: file, status: .wouldUpdate), + ] + + // -- Act -- + let output = AgentSkillInstallationRenderer().render(outcomes) + + // -- Assert -- + #expect(output.contains("Would install: new at")) + #expect(output.contains("Would update: old at")) + #expect(output.hasSuffix("Summary: 1 would install, 1 would update")) + } + + @Test("reports an empty selection rather than writing blank output") + func reportsNoInstallations() { + // -- Arrange -- + let renderer = AgentSkillInstallationRenderer() + + // -- Act -- + let output = renderer.render([]) + + // -- Assert -- + #expect(output == "No skills to process.") + } +} diff --git a/Tests/CLITests/skills/AgentSkillInstallationRecoveryTests.swift b/Tests/CLITests/skills/AgentSkillInstallationRecoveryTests.swift index 8f1b7cd..aaa23d4 100644 --- a/Tests/CLITests/skills/AgentSkillInstallationRecoveryTests.swift +++ b/Tests/CLITests/skills/AgentSkillInstallationRecoveryTests.swift @@ -135,6 +135,53 @@ struct AgentSkillInstallationRecoveryTests { #expect(try Data(contentsOf: file(root)) == Data("bundled".utf8)) } + @Test("list and update preview expose pending recovery without writing") + func listsAndPreviewsPendingUpdate() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + _ = try healthy.install([fixture("old")], root: root.path, dryRun: false, force: false) + let failing = installer(operation: .write, filename: ".apple-docs-managed.json") + #expect(throws: InjectedSkillFailure.self) { + try failing.update([fixture("new")], root: root.path, dryRun: false) + } + let journal = try Data(contentsOf: pending(root)) + let previousReceipt = try Data(contentsOf: receipt(root)) + + // -- Act -- + let listed = try healthy.list([fixture("new")], root: root.path) + let preview = try healthy.update([fixture("new")], root: root.path, dryRun: true) + let previewOutput = AgentSkillInstallationRenderer().render(preview) + let listOutput = AgentSkillInstallationRenderer().renderList(listed) + + // -- Assert -- + #expect(listOutput.first?.contains("installed (pending recovery)") == true) + #expect(previewOutput.contains("Would recover pending operation: apple-docs")) + #expect(try Data(contentsOf: pending(root)) == journal) + #expect(try Data(contentsOf: receipt(root)) == previousReceipt) + let recovered = try healthy.update([fixture("new")], root: root.path, dryRun: false) + #expect(recovered.map(\.status) == [.unchanged]) + #expect(!FileManager.default.fileExists(atPath: pending(root).path)) + #expect(try Data(contentsOf: file(root)) == Data("new".utf8)) + } + + @Test("list reports a missing managed file without repairing it") + func listsMissingManagedFile() throws { + // -- Arrange -- + let root = temporaryRoot() + defer { try? FileManager.default.removeItem(at: root) } + _ = try healthy.install([fixture("bundled")], root: root.path, dryRun: false, force: false) + try FileManager.default.removeItem(at: file(root)) + + // -- Act -- + let listed = try healthy.list([fixture("bundled")], root: root.path) + + // -- Assert -- + #expect(listed.map(\.status) == [.missing]) + #expect(!FileManager.default.fileExists(atPath: file(root).path)) + #expect(FileManager.default.fileExists(atPath: receipt(root).path)) + } + private var healthy: DefaultAgentSkillInstallationService { DefaultAgentSkillInstallationService(logger: Logger(label: "test") { _ in SwiftLogNoOpLogHandler() }) } diff --git a/Tests/CLITests/skills/AgentSkillInstallationServiceTests.swift b/Tests/CLITests/skills/AgentSkillInstallationServiceTests.swift index b19f962..d00198f 100644 --- a/Tests/CLITests/skills/AgentSkillInstallationServiceTests.swift +++ b/Tests/CLITests/skills/AgentSkillInstallationServiceTests.swift @@ -121,7 +121,7 @@ struct DefaultAgentSkillInstallationServiceTests { #expect(try String(contentsOf: skillFile(root), encoding: .utf8) == skill.content) let events = recorder.events.dropFirst(previousEventCount) #expect(events.contains { $0.level == .notice && $0.message.description == "Replacing modified managed skill" }) - #expect(events.contains { $0.level == .info && $0.message.description == "Installed skill" }) + #expect(events.contains { $0.level == .info && $0.message.description == "Updated skill" }) } @available(macOS 15, *)