From fb1958a4a5f2e85096e2f892bc1dfbb6ed2acafe Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 15:58:02 +0800 Subject: [PATCH 1/6] feat: add host plugins CLI commands and doctor governance output --- CHANGELOG.md | 16 + Documentation/Reference/CLI.md | 100 ++++- .../Reference/Schemas/doctor.schema.json | 38 +- Sources/CLI/EntryPoint.swift | 4 +- Sources/CLI/JSONReports.swift | 31 +- Sources/CLI/LifecycleCommands.swift | 9 +- Sources/CLI/PluginCommands.swift | 138 ++++++ Sources/CLI/PluginReports.swift | 132 ++++++ Tests/CLITests/CLIFixture.swift | 20 +- Tests/CLITests/ExecutableTests.swift | 4 +- Tests/CLITests/HostPluginCLITests.swift | 421 ++++++++++++++++++ 11 files changed, 885 insertions(+), 28 deletions(-) create mode 100644 Sources/CLI/PluginCommands.swift create mode 100644 Sources/CLI/PluginReports.swift create mode 100644 Tests/CLITests/HostPluginCLITests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 475c222..7927c00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## [0.4.0] - 2026-11-30 + +Built on agents-tools/core 0.4.0. + +### Added + +- List declared and observed host plugins with `agents plugins list`. Preview + changes with `agents plugins sync` and synchronize with `--apply`. +- Doctor reports advisory host plugin drift, skill collisions, legacy Codex + shared skill links, and skill listing budgets. + +### Changed + +- New user-scope Codex skill installations use `~/.codex/skills`. Use + `agents doctor --scope user --agent codex` to identify legacy shared links. + ## [0.3.1] - 2026-11-29 ### Added diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 1db688a..59e4c1d 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -3,7 +3,8 @@ `agents` manages declared agent components. Resolution, installation, state, and recovery operations use `AgentsCore`, `AgentsSkills`, and `AgentsInstructions`. Combined lifecycle, content audit, component inspection, -import and MCP tests use `AgentsUpdates`. `AgentsManifest` owns declaration +import, host plugin synchronization, skill governance, and MCP tests use +`AgentsUpdates`. `AgentsManifest` owns declaration parsing and editing, and the manifest dump contract. ## Commands @@ -31,6 +32,8 @@ agents components inventory [--scope project|user] agents components list [ --group --alias ] [--json] [--scope project|user] agents components add --group [--alias ] [--binding NAME=ENV_VAR] [--scope project|user] agents components remove [--kind ] [--identity ] [--occurrence ] [--agent ] [--binding NAME=ENV_VAR] [--scope project|user] +agents plugins list [--scope project|user] [--agent …] [--declared-only] [--json] +agents plugins sync [--scope project|user] [--agent …] [--apply] [--json] agents import --format [--root ] [--select ] [--apply | --json] [--binding NAME=ENV_VAR] [--scope project|user] agents bundle init --name --package-version agents bundle pack [--output | --publish-to ] [--reviewed-digest ] @@ -75,14 +78,14 @@ agents lifecycle trusted [--json] agents lifecycle untrust [ | --root-id ] [--json] agents install [--json] [--binding NAME=ENV_VAR] agents update [--apply | --json] [--binding NAME=ENV_VAR] [--replace] [--changing-access] -agents doctor [--root …] [--ci] [--require-organization-policy] [--json] +agents doctor [--scope project|user] [--agent …] [--root …] [--ci] [--require-organization-policy] [--json] agents export-patch [--scope project|user] [--dry-run] [-o ] [--json] agents audit [--scope project|user] [--file | --agent …] [--ci] [--format markdown|json|sarif] agents audit --file --strip [--scope project|user] [--apply] ``` `agents --help`, `agents skills --help`, `agents instructions --help`, -`agents watch --help`, `agents manifest --help`, `agents auth --help`, and each +`agents watch --help`, `agents plugins --help`, `agents manifest --help`, `agents auth --help`, and each command's `--help` describe their options. Running a group without a subcommand prints help, except `agents watch`, which runs `watch status` and accepts its options. `agents --version` @@ -109,14 +112,16 @@ Examples: | --- | --- | --- | | `--scope project\|user` | Where state lives: project (./.agent) or user (~/.agents). Default: project. | Commands with a scope option. Lifecycle trust commands use the current project or the user trust store. | | `--agent ` | Agent to install for: codex, claude-code, cursor, gemini-cli, opencode, or antigravity. Repeat for several. Default: the agents already recorded for this skill or source, else the declaration's agents, else codex and claude-code. | `skills add` | -| `--agent ` | Limit to this agent: codex, claude-code, cursor, gemini-cli, opencode, or antigravity. Repeat for several. Default: all recipients. | `skills list`, `skills remove`, `doctor` | +| `--agent ` | Limit to this agent: codex, claude-code, cursor, gemini-cli, opencode, or antigravity. Repeat for several. Default: all recipients. | `skills list`, `skills remove`, `plugins list`, `plugins sync`, `doctor` | | `--agent ` | Select instruction recipients. `add` can select Antigravity rules for specific sections. `remove` and `update` set the scope's instruction recipient list. Repeat for several. | `instructions add`, `instructions remove`, `instructions update` | | `--path ` | Search this subdirectory of the source. | Both kinds' `add` and `list `, `watch add` | | `--full-depth` | Discover recursively beyond conventional skill directories | `skills add`, `skills list ` | | `--mode link\|copy\|edit` | How to install: link (default), copy, or edit (a live link to a local source). | `skills add` | | `--root …` | Audit or map these project directories read-only. Repeat for several. | `doctor`, `instructions export` | | `--replace` | Take over target files that agents did not generate. | `instructions add`, `instructions update --apply` | -| `--json` | Emit a versioned JSON report on stdout | Both kinds' `list`, `install`, `doctor`, all update previews, `instructions export`, `watch status`, `watch diff`, `auth check`. `manifest dump` requires it. | +| `--declared-only` | Show only host plugins declared in the selected scope. | `plugins list` | +| `--apply` | Synchronize declared host plugins and verify the resulting state. | `plugins sync` | +| `--json` | Emit a versioned JSON report on stdout | Both kinds' `list`, `install`, `doctor`, all update previews, `plugins list`, `plugins sync`, `instructions export`, `watch status`, `watch diff`, `auth check`. `manifest dump` requires it. | Skill and instruction recipients are `codex`, `claude-code`, `cursor`, `gemini-cli`, `opencode`, and `antigravity`. Cursor instructions use @@ -126,7 +131,7 @@ recipients use the agents already recorded for the skill or source, then declaration defaults (initially Codex and Claude Code). On skill list, skill remove, and doctor, omission covers all recipients. Source listing shows available content regardless of recipients. -Doctor's agent filter limits skill installation checks; skill source checks and +Doctor's agent filter limits skill installation and governance checks. Skill source checks and instruction diagnostics cover the scope. Instruction targets can be shared by several agents, and are audited as physical files. @@ -208,6 +213,9 @@ is a usage error. Both require a Git repository for local sources and read committed content. `edit` links live local directories and accepts no requirement. +New Codex skill installations use `.agents/skills` in project scope and +`~/.codex/skills` in user scope by default. User scope honors `CODEX_HOME`. + Requirement options on add populate a source's `requirement` mapping in `agents.yaml`: @@ -415,6 +423,58 @@ Native component update previews print changed or unchanged component rows, symbolic before/after content, required binding names and permission changes. Completion lines identify the component and target after a successful apply. +## Host Plugins + +Add a `kind: hostPlugin` component to the selected scope's `agents.yaml` with a +name, explicit recipients, and either a `pluginId` or one bundle selected by +`source` and `path`. Set `enabled: false` to request disabled state. The default +is enabled. Core supports Codex, Claude Code, and Antigravity. Claude Code +defaults to the selected agents scope, with an optional `claudeScope` of +`user`, `project`, or `local`. + +`plugins list` reads local host records for the selected scope and reports +declared desired state, observed installation and enablement, locations and +drift. It includes unmanaged host entries by default. Use `--declared-only` +to show only declared entries. + +`plugins sync` previews commands and settings changes for the declarations in +the selected scope. Listing and previewing run zero subprocesses. Use +`--apply` to execute the planned vendor commands or settings edits and read +back the resulting host state. Antigravity project registration can use a +local bundle through workspace discovery settings. The ordinary `agents +install` and `agents update` lifecycle continues to manage `kind: plugin` +components separately. + +Completed previews exit 0. Applied sync exits 0 when every result is +`installed`, `enabled`, `disabled`, or `unchanged`. It reports all results +and exits 1 if any outcome is `unsupported`, `cliUnavailable`, +`authRequired`, `timeout`, or `failed`. + +### Host Plugin JSON + +`plugins list --json` emits `schemaVersion: 1`, `kind: "hostPlugins"`, +`scope`, and `plugins`. Each plugin has `agent`, `scope`, `name`, +`locations` (absolute filesystem paths), and `drift` (`current`, `missing`, +`enablement`, `unsupported`, or `unverified`). It includes `claudeScope`, +`pluginId`, `desiredEnabled`, `installed`, `explicitEnabled`, +`effectiveEnabled`, and `diagnostic` where available. Unmanaged entries omit +`desiredEnabled`. + +`plugins sync --json` emits `schemaVersion: 1`, `kind: "hostPluginSync"`, +`scope`, `applied`, `ok`, and `results`. Each result has `preview`, current +`status` in the same shape as a list entry, `commandsRun`, and optional +`outcome` and `diagnostic`. The preview contains the initial `status`, +`commands`, and `configurationChanges`. Commands are arrays of arguments with +the executable first. `commandsRun` contains attempts, including commands +that failed. Each configuration change contains an absolute `file` path, +a `key` array of settings path segments, optional `before`, and `after`. +Configuration values use a boolean for enablement, a string array for +replacement lists, and a string for a path to append. + +A dry run sets `applied: false` and `ok: true`, leaves `commandsRun` empty, +and omits `outcome`. An applied report sets `applied: true` and uses `ok` +to report whether every result succeeded. + ## Import `import --format [--root ]` previews one explicit @@ -907,6 +967,14 @@ Each root is an explicit project directory; `--root` cannot combine with user scope. A nonexistent root is an error. Without roots, project scope uses the current directory and user scope uses HOME. +Doctor also inspects declared host plugin drift, legacy Codex shared skill +links, and collisions between standalone and effectively enabled plugin +skills. It estimates each selected agent's listing size from deduplicated +skill names and descriptions in UTF-8 bytes. The advisory threshold is +8,000 bytes by default. Claude Code accepts a nonnegative integer override +through `SLASH_COMMAND_TOOL_CHAR_BUDGET`. Governance warnings remain advisory +under `--ci`. Doctor skips governance when transaction recovery is pending. + | Scope | Declaration | Lock | Cache | | --- | --- | --- | --- | | Project | `.agent/agents.yaml` | `.agent/agents.resolved` | `.agent/cache/` | @@ -1045,8 +1113,8 @@ final newline behavior; only diagnostics go to stderr. | Code | Meaning | | --- | --- | -| `0` | Success, including help/version, unchanged previews, and doctor warnings | -| `1` | Operation failure or a completed doctor report containing an error check | +| `0` | Success, including help/version, completed plugin previews, unchanged update previews, and doctor warnings | +| `1` | Operation failure, an applied plugin sync with a failed result, or a completed doctor report containing an error check | | `64` | Invalid usage, including unknown commands, options, or invalid option combinations | Unknown commands and subcommands report `Unknown command ''` and exit @@ -1061,8 +1129,9 @@ the skill `unresolved-transaction` check and both pending-recovery findings are errors. Other instruction diagnostics, including drift and missing targets, are warnings. Other skill severities are supplied by core. -A failed operation emits no successful JSON report. JSON stdout contains only -one object and a trailing newline; recovery notices remain on stderr. +A completed doctor or host plugin sync can emit a JSON report with `ok: false` +and exit 1. JSON stdout contains only one object and a trailing newline. +Recovery notices remain on stderr. ## JSON Schemas @@ -1103,6 +1172,8 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | `lifecycle … --json` | [Lifecycle reports](Schemas/lifecycle.schema.json) | `schemaVersion`, `kind` and fields for each command | | `install --json` | [Install](Schemas/install.schema.json) | `schemaVersion`, `scope`, `skills`, `instructions`, `components` | | `doctor --json` | [Doctor](Schemas/doctor.schema.json) | `schemaVersion`, `ok`, `roots` | +| `plugins list --json` | [Host plugin JSON contract](#host-plugin-json) | `schemaVersion`, `kind: "hostPlugins"`, `scope`, `plugins` | +| `plugins sync --json` | [Host plugin JSON contract](#host-plugin-json) | `schemaVersion`, `kind: "hostPluginSync"`, `scope`, `applied`, `ok`, `results` | | `components list --json` | [Components](Schemas/components-list.schema.json) | `schemaVersion`, `kind`, `scope`, `components` | | `import --json` | [Import](Schemas/import.schema.json) | `schemaVersion`, `kind`, `format`, `sources`, `components`, `diagnostics`, `bindings`, `resources` | | `mcp search --json` | [MCP registry search](Schemas/mcp-registry-page.schema.json) | `schemaVersion`, `servers` | @@ -1145,9 +1216,12 @@ Rows include unchanged membership and are sorted by agent ID. A missing lock means before membership is unrecorded. Regular skill file snapshots add boolean `executable`; existing `kind` and `base64` retain their meanings. These fields are optional in the schema. -Doctor checks add `kind: "skills" | "instructions" | "components"`; existing fields and IDs -remain, and instruction IDs use core's diagnostic names. Consumers distinguish -checks by `(kind, id)` because kinds may use the same ID. +Doctor checks use `kind` to identify skills, instructions, components, source +policy, organization policy, marketplace, or governance diagnostics. Consumers +distinguish checks by `(kind, id)` because kinds may use the same ID. A root +includes `skillBudgets` when estimates are available. Each budget contains +`agent`, `skills`, `utf8Bytes`, `advisoryThreshold`, and a description in +`estimate`. Roots with no estimates or pending recovery omit the property. The shared [instruction definitions](Schemas/instructions.schema.json) describe: diff --git a/Documentation/Reference/Schemas/doctor.schema.json b/Documentation/Reference/Schemas/doctor.schema.json index a415633..0ebc09e 100644 --- a/Documentation/Reference/Schemas/doctor.schema.json +++ b/Documentation/Reference/Schemas/doctor.schema.json @@ -55,7 +55,8 @@ "components", "sourcePolicy", "organizationPolicy", - "marketplace" + "marketplace", + "governance" ] } }, @@ -65,6 +66,41 @@ "message" ] } + }, + "skillBudgets": { + "type": "array", + "description": "Per-agent skill listing estimates. Omitted if no estimates are available or recovery is pending.", + "minItems": 1, + "items": { + "type": "object", + "properties": { + "agent": { + "type": "string" + }, + "skills": { + "type": "integer", + "minimum": 1 + }, + "utf8Bytes": { + "type": "integer", + "minimum": 0 + }, + "advisoryThreshold": { + "type": "integer", + "minimum": 0 + }, + "estimate": { + "type": "string" + } + }, + "required": [ + "agent", + "skills", + "utf8Bytes", + "advisoryThreshold", + "estimate" + ] + } } }, "required": [ diff --git a/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index ec080be..68d5aef 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -9,7 +9,7 @@ import Foundation #endif enum BuildInfo { - static let version = "0.3.1" + static let version = "0.4.0" } struct Agents: ParsableCommand { @@ -30,7 +30,7 @@ struct Agents: ParsableCommand { Skills.self, InstructionsCommand.self, Watch.self, Manifest.self, Install.self, Update.self, Doctor.self, ComponentsCommand.self, ImportCommand.self, MCPCommand.self, BundleCommand.self, MarketplaceCommand.self, AuthCommand.self, CacheCommand.self, PolicyCommand.self, - AuditCommand.self, ExportPatchCommand.self, LifecycleCommand.self, + AuditCommand.self, ExportPatchCommand.self, LifecycleCommand.self, PluginsCommand.self, ] ) diff --git a/Sources/CLI/JSONReports.swift b/Sources/CLI/JSONReports.swift index f7755fc..d8e71f6 100644 --- a/Sources/CLI/JSONReports.swift +++ b/Sources/CLI/JSONReports.swift @@ -260,11 +260,12 @@ struct DoctorRoot: Encodable { let scope: String let ok: Bool let checks: [CheckItem] + let skillBudgets: [SkillBudgetItem]? init( root: String, scope: String, report: DoctorReport, instructions: InstructionDoctorReport, environment: RuntimeEnvironment, inventory: ScopeInspection? = nil, - policyChecks: [CheckItem] = [], ci: Bool = false + policyChecks: [CheckItem] = [], governance: SkillGovernanceReport? = nil, ci: Bool = false ) { self.root = root self.scope = scope @@ -273,7 +274,29 @@ struct DoctorRoot: Encodable { + instructions.diagnostics.map { CheckItem($0, environment: environment, ci: ci) } + (inventory.map { CheckItem.inventory($0, environment: environment) } ?? []) + policyChecks + + (governance?.checks.map(CheckItem.init) ?? []) ok = !checks.contains { $0.status == "error" } + if let budgets = governance?.skillBudgets, !budgets.isEmpty { + skillBudgets = budgets.map(SkillBudgetItem.init) + } else { + skillBudgets = nil + } + } +} + +struct SkillBudgetItem: Encodable { + let agent: String + let skills: Int + let utf8Bytes: Int + let advisoryThreshold: Int + let estimate: String + + init(_ budget: SkillListingBudget) { + agent = budget.agent.rawValue + skills = budget.skills + utf8Bytes = budget.utf8Bytes + advisoryThreshold = budget.advisoryThreshold + estimate = budget.estimate } } @@ -334,6 +357,12 @@ struct CheckItem: Encodable { path: finding.document.map { $0.isFileURL ? $0.path : $0.absoluteString }) } + init(_ check: SkillGovernanceCheck) { + self.init( + kind: "governance", id: check.id, status: check.status.rawValue, message: check.message, + path: check.path) + } + init(kind: String, id: String, status: String, message: String, path: String?) { self.kind = kind self.id = id diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index 44d7b18..8596516 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -139,7 +139,7 @@ struct Doctor: ParsableCommand { commandName: "doctor", abstract: "Compare all managed components with the lock and report problems.", discussion: - "The --agent filter limits skill installation checks. Instructions are audited across the scope's physical targets." + "The --agent filter limits skill installation and governance checks. Instructions are audited across the scope's physical targets." ) @OptionGroup var location: ScopeOptions @OptionGroup var agents: AgentOptions @@ -181,10 +181,14 @@ struct Doctor: ParsableCommand { let instructions = try InstructionOperations.doctor( scope: location.scope, environment: runtime) let inventory = try UpdateOperations.inspect(scope: location.scope, environment: runtime) + let governance: SkillGovernanceReport? let policyChecks: [CheckItem] if inventory.recovery.pending { + governance = nil policyChecks = [] } else { + governance = try SkillGovernance.inspect( + scope: location.scope, agents: agents.recipients, environment: runtime) do { let hasSelection = runtime.userOrganizationPolicy != nil @@ -232,7 +236,8 @@ struct Doctor: ParsableCommand { DoctorRoot( root: location.scope == .user ? environment.homeDirectory.path : project.path, scope: location.scope.rawValue, report: report, instructions: instructions, - environment: runtime, inventory: inventory, policyChecks: policyChecks, ci: ci)) + environment: runtime, inventory: inventory, policyChecks: policyChecks, + governance: governance, ci: ci)) } let report = DoctorOutput(roots: reports) if json { diff --git a/Sources/CLI/PluginCommands.swift b/Sources/CLI/PluginCommands.swift new file mode 100644 index 0000000..6184d2e --- /dev/null +++ b/Sources/CLI/PluginCommands.swift @@ -0,0 +1,138 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser + +struct PluginsCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "plugins", + abstract: "Inspect and synchronize host plugins.", + subcommands: [ListHostPlugins.self, SyncHostPlugins.self]) +} + +struct ListHostPlugins: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "list", abstract: "Inspect declared and observed host plugins.") + + @OptionGroup var location: ScopeOptions + @OptionGroup var agents: AgentOptions + @Flag(help: "Show only plugins declared in the selected scope.") var declaredOnly = false + @Flag(help: "Print the versioned JSON report.") var json = false + + func run() throws { + let runtime = RuntimeEnvironment() + let scope = location.scope + let plugins = try HostPluginExecutor.inspect( + scope: scope, agents: agents.recipients, environment: runtime, includeUnmanaged: !declaredOnly + ) + let report = HostPluginListReport(scope: scope, plugins: plugins) + if json { + try Terminal.json(report) + } else if report.plugins.isEmpty { + Terminal.write("No host plugins found.\n") + } else { + let paths = HumanPaths(scope: scope, environment: runtime) + for plugin in report.plugins { + var state = [plugin.drift] + if let installed = plugin.installed { + state.append(installed ? "installed" : "not installed") + } + if let enabled = plugin.effectiveEnabled { + state.append(enabled ? "enabled" : "disabled") + } + if let desired = plugin.desiredEnabled, desired != plugin.effectiveEnabled { + state.append(desired ? "wanted enabled" : "wanted disabled") + } + Terminal.write("\(plugin.label): \(state.joined(separator: ", "))\n") + for path in plugin.locations { + Terminal.write(" \(paths.path(path))\n") + } + if let diagnostic = plugin.diagnostic { + Terminal.write(" \(Terminal.line(diagnostic))\n") + } + } + } + } +} + +struct SyncHostPlugins: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "sync", abstract: "Preview or apply declared host plugin changes.") + + @OptionGroup var location: ScopeOptions + @OptionGroup var agents: AgentOptions + @Flag(help: "Synchronize host plugins and verify the resulting state.") var apply = false + @Flag(help: "Print the versioned JSON report.") var json = false + + func run() async throws { + let runtime = RuntimeEnvironment() + let scope = location.scope + let results = try await HostPluginExecutor.sync( + scope: scope, agents: agents.recipients, apply: apply, environment: runtime) + let report = HostPluginSyncReport(scope: scope, applied: apply, results: results) + if json { + try Terminal.json(report) + } else { + printSync(report, paths: HumanPaths(scope: scope, environment: runtime)) + } + if !report.ok { throw ExitCode.failure } + } + + private func printSync(_ report: HostPluginSyncReport, paths: HumanPaths) { + if report.results.isEmpty { + Terminal.write("No host plugins declared.\n") + return + } + var hasChanges = false + for result in report.results { + let status = result.status + let summary = result.outcome.map { "\($0) (\(status.drift))" } ?? status.drift + Terminal.write("\(status.label): \(summary)\n") + if let diagnostic = result.diagnostic ?? status.diagnostic { + Terminal.write(" \(Terminal.line(diagnostic))\n") + } + guard !report.applied else { continue } + for command in result.preview.commands { + let arguments = command.map { argument in + argument.isEmpty || argument.contains(where: \.isWhitespace) + ? argument.debugDescription : Terminal.line(argument) + }.joined(separator: " ") + Terminal.write(" Command \(arguments)\n") + } + for change in result.preview.configurationChanges { + let key = Terminal.line(change.key.joined(separator: ".")) + let file = paths.path(change.file) + Terminal.write(" \(file) \(key) \(change.summary(paths: paths))\n") + } + hasChanges = + hasChanges || !result.preview.commands.isEmpty + || !result.preview.configurationChanges.isEmpty + } + if hasChanges { + Terminal.write("Preview only. Run again with --apply to synchronize host plugins.\n") + } + } +} + +extension HostPluginItem { + fileprivate var label: String { + let id = pluginId.flatMap { $0 == name ? nil : " (\(Terminal.line($0)))" } ?? "" + return "\(agent) \(Terminal.line(name))\(id) [\(claudeScope ?? scope)]" + } +} + +extension HostPluginSyncReport.ConfigurationChange { + fileprivate func summary(paths: HumanPaths) -> String { + if case .appendPath(let path) = after { return "append \(paths.path(path))" } + return "\(before?.description ?? "(unset)") → \(after.description)" + } +} + +extension HostPluginSyncReport.Value { + fileprivate var description: String { + switch self { + case .boolean(let value): String(value) + case .strings(let values): values.debugDescription + case .appendPath(let path): path.debugDescription + } + } +} diff --git a/Sources/CLI/PluginReports.swift b/Sources/CLI/PluginReports.swift new file mode 100644 index 0000000..ca29553 --- /dev/null +++ b/Sources/CLI/PluginReports.swift @@ -0,0 +1,132 @@ +import AgentsCore +import AgentsUpdates + +struct HostPluginListReport: Encodable { + let schemaVersion = 1 + let kind = "hostPlugins" + let scope: String + let plugins: [HostPluginItem] + + init(scope: InstallScope, plugins: [HostPluginStatus]) { + self.scope = scope.rawValue + self.plugins = plugins.map(HostPluginItem.init) + } +} + +struct HostPluginSyncReport: Encodable { + let schemaVersion = 1 + let kind = "hostPluginSync" + let scope: String + let applied: Bool + let ok: Bool + let results: [Result] + + init(scope: InstallScope, applied: Bool, results: [HostPluginSyncResult]) { + self.scope = scope.rawValue + self.applied = applied + self.results = results.map(Result.init) + ok = + !applied + || results.allSatisfy { result in + switch result.outcome { + case .installed, .enabled, .disabled, .unchanged: true + case .unsupported, .cliUnavailable, .authRequired, .timeout, .failed, nil: false + } + } + } + + struct Result: Encodable { + let preview: Preview + let status: HostPluginItem + let outcome: String? + let commandsRun: [[String]] + let diagnostic: String? + + init(_ result: HostPluginSyncResult) { + preview = Preview(result.preview) + status = HostPluginItem(result.status) + outcome = result.outcome?.rawValue + commandsRun = result.commandsRun + diagnostic = result.diagnostic + } + } + + struct Preview: Encodable { + let status: HostPluginItem + let commands: [[String]] + let configurationChanges: [ConfigurationChange] + + init(_ preview: HostPluginPreview) { + status = HostPluginItem(preview.status) + commands = preview.commands + configurationChanges = preview.configurationChanges.map(ConfigurationChange.init) + } + } + + struct ConfigurationChange: Encodable { + let file: String + let key: [String] + let before: Value? + let after: Value + + init(_ change: HostPluginConfigurationChange) { + file = change.file.path + key = change.key + before = change.before.map(Value.init) + after = Value(change.after) + } + } + + enum Value: Encodable { + case boolean(Bool) + case strings([String]) + case appendPath(String) + + init(_ value: HostPluginConfigurationValue) { + switch value { + case .boolean(let enabled): self = .boolean(enabled) + case .strings(let values): self = .strings(values) + case .appendPath(let path): self = .appendPath(path) + } + } + + func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .boolean(let value): try container.encode(value) + case .strings(let values): try container.encode(values) + case .appendPath(let path): try container.encode(path) + } + } + } +} + +struct HostPluginItem: Encodable { + let agent: String + let scope: String + let claudeScope: String? + let name: String + let pluginId: String? + let desiredEnabled: Bool? + let installed: Bool? + let explicitEnabled: Bool? + let effectiveEnabled: Bool? + let locations: [String] + let drift: String + let diagnostic: String? + + init(_ status: HostPluginStatus) { + agent = status.agent.rawValue + scope = status.scope.rawValue + claudeScope = status.claudeScope?.rawValue + name = status.name + pluginId = status.pluginId + desiredEnabled = status.desiredEnabled + installed = status.installed + explicitEnabled = status.explicitEnabled + effectiveEnabled = status.effectiveEnabled + locations = status.locations.map(\.path) + drift = status.drift.rawValue + diagnostic = status.diagnostic + } +} diff --git a/Tests/CLITests/CLIFixture.swift b/Tests/CLITests/CLIFixture.swift index 56e3765..e951964 100644 --- a/Tests/CLITests/CLIFixture.swift +++ b/Tests/CLITests/CLIFixture.swift @@ -44,7 +44,9 @@ final class CLIFixture { deinit { try? FileManager.default.removeItem(at: root) } - func run(_ arguments: [String], directory: URL? = nil) throws -> CLIResult { + func run( + _ arguments: [String], directory: URL? = nil, environment overrides: [String: String] = [:] + ) throws -> CLIResult { let package = URL(fileURLWithPath: #filePath).deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent() // SwiftPM builds the executable dependency for the active test configuration. @@ -60,12 +62,15 @@ final class CLIFixture { ] let executable = try #require( candidates.first { FileManager.default.isExecutableFile(atPath: $0.path) }) - return try process(executable, arguments, directory: directory ?? project) + return try process( + executable, arguments, directory: directory ?? project, overrides: overrides) } @discardableResult - func success(_ arguments: [String], directory: URL? = nil) throws -> CLIResult { - let result = try run(arguments, directory: directory) + func success( + _ arguments: [String], directory: URL? = nil, environment overrides: [String: String] = [:] + ) throws -> CLIResult { + let result = try run(arguments, directory: directory, environment: overrides) try #require(result.status == 0, "\(arguments): \(result.stderr)") #expect(result.stderr.isEmpty) return result @@ -141,8 +146,9 @@ final class CLIFixture { """) } - private func process(_ executable: URL, _ arguments: [String], directory: URL) throws -> CLIResult - { + private func process( + _ executable: URL, _ arguments: [String], directory: URL, overrides: [String: String] = [:] + ) throws -> CLIResult { let stdout = root.appendingPathComponent("stdout") let stderr = root.appendingPathComponent("stderr") try Data().write(to: stdout) @@ -157,7 +163,7 @@ final class CLIFixture { process.executableURL = executable process.arguments = arguments process.currentDirectoryURL = directory - process.environment = environment + process.environment = environment.merging(overrides) { _, override in override } process.standardInput = FileHandle.nullDevice process.standardOutput = output process.standardError = errors diff --git a/Tests/CLITests/ExecutableTests.swift b/Tests/CLITests/ExecutableTests.swift index 693b258..9ce58d9 100644 --- a/Tests/CLITests/ExecutableTests.swift +++ b/Tests/CLITests/ExecutableTests.swift @@ -28,7 +28,7 @@ struct ExecutableTests { let installed = URL(fileURLWithPath: try #require(item["path"] as? String)) #expect(installed.path.hasPrefix(fixture.root.path)) let humanList = try fixture.success(["skills", "list"] + scopeArguments).stdout - let displayPath = scope == "user" ? "~/.agents/skills/demo" : ".agents/skills/demo" + let displayPath = scope == "user" ? "~/.codex/skills/demo" : ".agents/skills/demo" #expect(humanList.contains(displayPath)) #expect(!humanList.contains(installed.path)) let lock = try Data(contentsOf: fixture.state("agents.resolved", scope: scope)) @@ -394,7 +394,7 @@ struct ExecutableTests { ]) #expect( FileManager.default.fileExists( - atPath: fixture.home.appendingPathComponent(".agents/skills/unknown/SKILL.md").path)) + atPath: fixture.home.appendingPathComponent(".codex/skills/unknown/SKILL.md").path)) } @Test func rootHelpExamples() throws { diff --git a/Tests/CLITests/HostPluginCLITests.swift b/Tests/CLITests/HostPluginCLITests.swift new file mode 100644 index 0000000..e9ca24b --- /dev/null +++ b/Tests/CLITests/HostPluginCLITests.swift @@ -0,0 +1,421 @@ +import Foundation +import Testing + +struct HostPluginCLITests { + @Test func emptyListUsesVersionedReportAndLeavesStateAbsent() throws { + let fixture = try CLIFixture() + let report = try fixture.success(["plugins", "list", "--json"]).json() + #expect(Set(report.keys) == ["schemaVersion", "kind", "scope", "plugins"]) + #expect(report["schemaVersion"] as? Int == 1) + #expect(report["kind"] as? String == "hostPlugins") + #expect(report["scope"] as? String == "project") + #expect((report["plugins"] as? [Any])?.isEmpty == true) + let human = try fixture.success(["plugins", "list"]).stdout + #expect(human == "No host plugins found.\n") + #expect(try FileManager.default.contentsOfDirectory(atPath: fixture.project.path).isEmpty) + #expect(try FileManager.default.contentsOfDirectory(atPath: fixture.home.path).isEmpty) + } + + @Test func listShowsObservedStateAndFiltersDeclarationsAndAgents() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + components: + - {kind: hostPlugin, name: missing, pluginId: docs@work, agents: [codex]} + - {kind: hostPlugin, name: review, pluginId: review@work, agents: [claude-code], claudeScope: local} + """, scope: "user") + let config = fixture.home.appendingPathComponent(".codex/config.toml") + try write(#"[plugins."other@work"]"# + "\nenabled = false\n", to: config) + let bundle = fixture.home.appendingPathComponent(".codex/plugins/cache/work/other/1") + try write( + #"{"name":"other"}"#, to: bundle.appendingPathComponent(".codex-plugin/plugin.json")) + let args = ["plugins", "list", "--scope", "user"] + let report = try fixture.success(args + ["--json"]).json() + let plugins = try #require(report["plugins"] as? [[String: Any]]) + #expect(report["scope"] as? String == "user") + #expect(plugins.count == 3) + let byName = Dictionary(grouping: plugins, by: { $0["name"] as? String }) + let missing = try #require(byName["missing"]?.first) + #expect(missing["drift"] as? String == "missing") + #expect(missing["desiredEnabled"] as? Bool == true) + #expect(missing["installed"] as? Bool == false) + #expect(missing["pluginId"] as? String == "docs@work") + #expect(missing["agent"] as? String == "codex" && missing["scope"] as? String == "user") + #expect(byName["review"]?.first?["claudeScope"] as? String == "local") + let unmanaged = try #require(byName["other"]?.first) + #expect(unmanaged["desiredEnabled"] == nil) + #expect(unmanaged["drift"] as? String == "current") + #expect(unmanaged["installed"] as? Bool == true) + #expect(unmanaged["explicitEnabled"] as? Bool == false) + #expect(unmanaged["effectiveEnabled"] as? Bool == false) + let locations = try #require(unmanaged["locations"] as? [String]) + #expect(locations.count == 1) + let location = try #require(locations.first) + #expect(location.hasPrefix("/")) + #expect( + URL(fileURLWithPath: location).resolvingSymlinksInPath().path + == bundle.resolvingSymlinksInPath().path) + + let declared = try fixture.success(args + ["--declared-only", "--json"]).json() + let declaredPlugins = try #require(declared["plugins"] as? [[String: Any]]) + #expect(Set(declaredPlugins.compactMap { $0["name"] as? String }) == ["missing", "review"]) + let filtered = try fixture.success(args + ["--agent", "codex", "--json"]).json() + let filteredPlugins = try #require(filtered["plugins"] as? [[String: Any]]) + #expect(filteredPlugins.count == 2) + #expect(filteredPlugins.allSatisfy { $0["agent"] as? String == "codex" }) + let human = try fixture.success(args).stdout + #expect(human.contains("codex other (other@work) [user]: current, installed, disabled")) + #expect(human.contains("~/.codex/plugins/cache/work/other/1")) + } + + @Test func listAndSyncPreviewRunNoVendorCommandsOrSettingsEdits() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex]} + - {kind: hostPlugin, name: review, pluginId: review@work, agents: [claude-code]} + - {kind: hostPlugin, name: local, source: ".", path: bundles/local, agents: [antigravity]} + """) + try write( + #"{"name":"local"}"#, to: fixture.project.appendingPathComponent("bundles/local/plugin.json")) + for executable in ["codex", "claude", "agy"] { + try shim(executable, body: "exit 9", fixture: fixture) + } + let environment = ["PATH": fixture.root.path] + try fixture.success(["plugins", "list", "--json"], environment: environment) + let args = ["plugins", "sync", "--agent", "codex", "--agent", "antigravity"] + let report = try fixture.success(args + ["--json"], environment: environment).json() + #expect(Set(report.keys) == ["schemaVersion", "kind", "scope", "applied", "ok", "results"]) + #expect(report["schemaVersion"] as? Int == 1) + #expect(report["kind"] as? String == "hostPluginSync") + #expect(report["scope"] as? String == "project") + #expect(report["applied"] as? Bool == false && report["ok"] as? Bool == true) + let results = try #require(report["results"] as? [[String: Any]]) + #expect(results.count == 2) + #expect( + results.allSatisfy { + $0["outcome"] == nil && ($0["commandsRun"] as? [Any])?.isEmpty == true + }) + let codex = try #require(results.first?["preview"] as? [String: Any]) + let initial = try #require(codex["status"] as? [String: Any]) + let observed = try #require(results.first?["status"] as? [String: Any]) + #expect(initial["drift"] as? String == "missing") + #expect(observed["drift"] as? String == "missing" && observed["agent"] as? String == "codex") + #expect( + codex["commands"] as? [[String]] == [["codex", "plugin", "add", "github@curated", "--json"]]) + let changes = try #require(codex["configurationChanges"] as? [[String: Any]]) + let change = try #require(changes.first) + #expect( + change["file"] as? String == fixture.project.appendingPathComponent(".codex/config.toml").path + ) + #expect(change["key"] as? [String] == ["plugins", "github@curated", "enabled"]) + #expect(change["before"] == nil && change["after"] as? Bool == true) + let agy = try #require(results.last?["preview"] as? [String: Any]) + let registration = try #require((agy["configurationChanges"] as? [[String: Any]])?.first) + #expect(registration["key"] as? [String] == ["entries"]) + #expect(registration["after"] as? String == "bundles/local") + let human = try fixture.success(args, environment: environment).stdout + #expect(human.contains("codex plugin add github@curated --json")) + #expect(human.contains(".codex/config.toml plugins.github@curated.enabled")) + #expect(human.contains(".agents/plugins.json entries append bundles/local")) + #expect(human.contains("Preview only. Run again with --apply to synchronize host plugins.")) + #expect( + !FileManager.default.fileExists(atPath: fixture.home.appendingPathComponent("calls").path)) + for path in [".codex", ".agents"] { + #expect( + !FileManager.default.fileExists(atPath: fixture.project.appendingPathComponent(path).path)) + } + } + + @Test func appliedSyncInstallsAndTogglesWithReadback() throws { + let fixture = try CLIFixture() + let manifest = """ + version: 1 + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex], enabled: false} + - {kind: hostPlugin, name: review, pluginId: review@work, agents: [claude-code], enabled: false} + - {kind: hostPlugin, name: notes, pluginId: notes, agents: [antigravity], enabled: false} + """ + try fixture.writeManifest(manifest, scope: "user") + try shim( + "codex", + body: #""" + test "$*" = "plugin add github@curated --json" || exit 2 + cache="$HOME/.codex/plugins/cache/curated/github/1" + /bin/mkdir -p "$cache/.codex-plugin" + printf '%s\n' '{"name":"github"}' > "$cache/.codex-plugin/plugin.json" + /bin/cat > "$HOME/.codex/config.toml" <<'EOF' + # Preserve this host setting. + model = "keep" + [plugins."github@curated"] + enabled = true + [mcp_servers.custom] + command = "keep" + EOF + """#, fixture: fixture) + try shim( + "claude", + body: #""" + case "$*" in + "plugin install review@work --scope user") + bundle="$HOME/.claude/plugins/cache/review" + /bin/mkdir -p "$bundle" + printf '{"plugins":{"review@work":[{"scope":"user","installPath":"%s"}]}}\n' "$bundle" \ + > "$HOME/.claude/plugins/installed_plugins.json" + ;; + "plugin disable review@work --scope user" | "plugin enable review@work --scope user") + enabled=false + if test "$2" = enable; then enabled=true; fi + printf '{"enabledPlugins":{"review@work":%s}}\n' "$enabled" \ + > "$HOME/.claude/settings.json" + ;; + *) exit 2 ;; + esac + """#, fixture: fixture) + try shim( + "agy", + body: #""" + case "$*" in + "plugin install notes") + /bin/mkdir -p "$HOME/.gemini/config/plugins/notes" + printf '%s\n' '{"name":"notes"}' > "$HOME/.gemini/config/plugins/notes/plugin.json" + ;; + "plugin disable notes" | "plugin enable notes") + enabled=false + if test "$2" = enable; then enabled=true; fi + printf '{"plugins":{"notes":{"enabled":%s}}}\n' "$enabled" > "$HOME/.gemini/config/config.json" + ;; + *) exit 2 ;; + esac + """#, fixture: fixture) + + let environment = ["PATH": fixture.root.path] + let args = ["plugins", "sync", "--scope", "user", "--apply"] + let report = try fixture.success(args + ["--json"], environment: environment).json() + #expect(report["scope"] as? String == "user") + #expect(report["applied"] as? Bool == true && report["ok"] as? Bool == true) + let results = try #require(report["results"] as? [[String: Any]]) + #expect(results.map { $0["outcome"] as? String } == ["installed", "installed", "installed"]) + #expect( + results.compactMap { $0["commandsRun"] as? [[String]] } == [ + [["codex", "plugin", "add", "github@curated", "--json"]], + [ + ["claude", "plugin", "install", "review@work", "--scope", "user"], + ["claude", "plugin", "disable", "review@work", "--scope", "user"], + ], + [["agy", "plugin", "install", "notes"], ["agy", "plugin", "disable", "notes"]], + ]) + let statuses = results.compactMap { $0["status"] as? [String: Any] } + #expect(statuses.count == 3) + #expect( + statuses.allSatisfy { + $0["drift"] as? String == "current" && $0["installed"] as? Bool == true + && $0["explicitEnabled"] as? Bool == false && $0["effectiveEnabled"] as? Bool == false + }) + let config = fixture.home.appendingPathComponent(".codex/config.toml") + let bytes = try String(contentsOf: config, encoding: .utf8) + #expect(bytes.contains("enabled = false")) + #expect(bytes.contains("# Preserve this host setting.")) + #expect(bytes.contains("model = \"keep\"") && bytes.contains("command = \"keep\"")) + + try fixture.writeManifest( + manifest.replacingOccurrences(of: "enabled: false", with: "enabled: true"), scope: "user") + let human = try fixture.success(args, environment: environment).stdout + #expect(human.contains("codex github (github@curated) [user]: enabled (current)")) + #expect(human.contains("claude-code review (review@work) [user]: enabled (current)")) + #expect(human.contains("antigravity notes [user]: enabled (current)")) + #expect( + try String(contentsOf: config, encoding: .utf8) + == bytes.replacingOccurrences( + of: "enabled = false", with: "enabled = true")) + let repeated = try fixture.success(args + ["--json"], environment: environment).json() + let unchanged = try #require(repeated["results"] as? [[String: Any]]) + #expect(unchanged.map { $0["outcome"] as? String } == ["unchanged", "unchanged", "unchanged"]) + let calls = try String( + contentsOf: fixture.home.appendingPathComponent("calls"), encoding: .utf8) + #expect( + calls.split(separator: "\n").map(String.init) == [ + "codex plugin add github@curated --json", + "claude plugin install review@work --scope user", + "claude plugin disable review@work --scope user", + "agy plugin install notes", + "agy plugin disable notes", + "claude plugin enable review@work --scope user", + "agy plugin enable notes", + ]) + } + + @Test func failedApplyReturnsAllOutcomesAndExitOne() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + components: + - {kind: hostPlugin, name: github, pluginId: github@curated, agents: [codex]} + - {kind: hostPlugin, name: review, pluginId: review@work, agents: [claude-code]} + - {kind: hostPlugin, name: notes, pluginId: notes, agents: [antigravity]} + """) + try shim("claude", body: "echo 'Authentication required' >&2\nexit 1", fixture: fixture) + let environment = ["PATH": fixture.root.path] + let args = ["plugins", "sync", "--json"] + let preview = try fixture.success(args, environment: environment).json() + #expect(preview["ok"] as? Bool == true) + #expect( + !FileManager.default.fileExists(atPath: fixture.home.appendingPathComponent("calls").path)) + let failure = try fixture.run(args + ["--apply"], environment: environment) + #expect(failure.status == 1 && failure.stderr.isEmpty) + let report = try failure.json() + #expect(report["applied"] as? Bool == true && report["ok"] as? Bool == false) + let results = try #require(report["results"] as? [[String: Any]]) + #expect( + results.map { $0["outcome"] as? String } == ["cliUnavailable", "authRequired", "unsupported"]) + #expect( + results.last?["diagnostic"] as? String + == "A project Antigravity plugin needs a local bundle or an existing installation.") + #expect(results.last?["commandsRun"] as? [[String]] == []) + + for (agent, outcome) in [ + ("codex", "cliUnavailable"), ("claude-code", "authRequired"), ("antigravity", "unsupported"), + ] { + let failure = try fixture.run(args + ["--apply", "--agent", agent], environment: environment) + #expect(failure.status == 1 && failure.stderr.isEmpty) + let filtered = try failure.json() + let rows = try #require(filtered["results"] as? [[String: Any]]) + #expect(rows.map { $0["outcome"] as? String } == [outcome]) + } + } + + @Test func doctorOmitsSkillBudgetsForEmptyRoot() throws { + let fixture = try CLIFixture() + let report = try fixture.success(["doctor", "--json"]).json() + let root = try doctorRoot(report) + #expect(Set(root.keys) == ["root", "scope", "ok", "checks"]) + #expect((root["checks"] as? [Any])?.isEmpty == true) + #expect(try fixture.success(["doctor"]).stdout == ". (project)\n No problems found.\n") + } + + @Test func doctorReportsLegacyCodexLinkInUserScope() throws { + let fixture = try CLIFixture() + try fixture.skill() + try fixture.commit() + try fixture.success([ + "skills", "add", fixture.source.path, "demo", "--scope", "user", "--agent", "codex", + "--mode", "copy", + ]) + let privateSkill = fixture.home.appendingPathComponent(".codex/skills/demo") + let legacy = fixture.home.appendingPathComponent(".agents/skills/demo") + try FileManager.default.createDirectory( + at: legacy.deletingLastPathComponent(), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: legacy, withDestinationURL: privateSkill) + let report = try fixture.success([ + "doctor", "--scope", "user", "--agent", "codex", "--ci", "--json", + ]).json() + let root = try doctorRoot(report) + let checks = try #require(root["checks"] as? [[String: Any]]) + let warning = try #require(checks.first { $0["id"] as? String == "codex-legacy-skill-link" }) + #expect(warning["kind"] as? String == "governance" && warning["status"] as? String == "warning") + #expect(warning["path"] as? String == legacy.path) + #expect(report["ok"] as? Bool == true && root["ok"] as? Bool == true) + #expect( + try FileManager.default.destinationOfSymbolicLink(atPath: legacy.path) == privateSkill.path) + } + + @Test func doctorFiltersSkillCollisionsAndBudgetWarningsByAgent() throws { + let fixture = try CLIFixture() + let plugin = fixture.home.appendingPathComponent(".claude/plugins/cache/work/tools") + let standalone = fixture.project.appendingPathComponent(".claude/skills/review/SKILL.md") + try write( + "---\nname: review\ndescription: Révision\n---\n\nBody\n", + to: standalone) + try write( + #"{"name":"tools"}"#, + to: plugin.appendingPathComponent(".claude-plugin/plugin.json")) + try write( + "---\nname: review\ndescription: Plugin\n---\n\nBody\n", + to: plugin.appendingPathComponent("skills/review/SKILL.md")) + try write( + """ + {"plugins":{"tools@work":[{"scope":"user","installPath":"\(plugin.path)"}]}} + """, to: fixture.home.appendingPathComponent(".claude/plugins/installed_plugins.json")) + + let codexPlugin = fixture.home.appendingPathComponent(".codex/plugins/cache/curated/pack/1.0.0") + try write( + "---\nname: review\ndescription: Standalone\n---\n\nBody\n", + to: fixture.home.appendingPathComponent(".codex/skills/review/SKILL.md")) + try write( + #"{"name":"pack"}"#, + to: codexPlugin.appendingPathComponent(".codex-plugin/plugin.json")) + try write( + "---\nname: review\ndescription: Plugin\n---\n\nBody\n", + to: codexPlugin.appendingPathComponent("skills/review/SKILL.md")) + try write( + "[plugins.\"pack@curated\"]\nenabled = true\n", + to: fixture.home.appendingPathComponent(".codex/config.toml")) + + let args = ["doctor", "--ci", "--json"] + let environment = ["SLASH_COMMAND_TOOL_CHAR_BUDGET": "4"] + let report = try fixture.success(args + ["--agent", "claude-code"], environment: environment) + .json() + let root = try doctorRoot(report) + #expect(report["ok"] as? Bool == true && root["ok"] as? Bool == true) + let checks = try #require(root["checks"] as? [[String: Any]]) + #expect(Set(checks.compactMap { $0["id"] as? String }) == ["skill-listing-budget"]) + #expect( + checks.allSatisfy { + $0["kind"] as? String == "governance" && $0["status"] as? String == "warning" + }) + let budgets = try #require(root["skillBudgets"] as? [[String: Any]]) + #expect(budgets.count == 1) + let budget = try #require(budgets.first) + #expect(Set(budget.keys) == ["agent", "skills", "utf8Bytes", "advisoryThreshold", "estimate"]) + #expect(budget["agent"] as? String == "claude-code") + let expectedClaudeBytes = + "reviewRévision".utf8.count + "tools:reviewPlugin".utf8.count + #expect(budget["skills"] as? Int == 2 && budget["utf8Bytes"] as? Int == expectedClaudeBytes) + #expect(budget["advisoryThreshold"] as? Int == 4) + #expect((budget["estimate"] as? String)?.contains("UTF-8 bytes") == true) + + let codexReport = try fixture.success(args + ["--agent", "codex"], environment: environment) + .json() + let codexRoot = try doctorRoot(codexReport) + let codexChecks = try #require(codexRoot["checks"] as? [[String: Any]]) + #expect( + Set(codexChecks.compactMap { $0["id"] as? String }) == ["plugin-skill-divergentTarget"]) + #expect( + codexChecks.allSatisfy { + $0["kind"] as? String == "governance" && $0["status"] as? String == "warning" + }) + + let filtered = try fixture.success( + args + ["--agent", "antigravity"], environment: environment + ).json() + let filteredRoot = try doctorRoot(filtered) + #expect((filteredRoot["checks"] as? [Any])?.isEmpty == true) + #expect(filteredRoot["skillBudgets"] == nil) + } + + private func doctorRoot(_ report: [String: Any]) throws -> [String: Any] { + try #require((report["roots"] as? [[String: Any]])?.first) + } + + private func shim(_ name: String, body: String, fixture: CLIFixture) throws { + let file = fixture.root.appendingPathComponent(name) + try write( + #""" + #!/bin/sh + printf '%s %s\n' '\#(name)' "$*" >> "$HOME/calls" + \#(body) + + """#, to: file) + try FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: file.path) + } + + private func write(_ text: String, to file: URL) throws { + try FileManager.default.createDirectory( + at: file.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(text.utf8).write(to: file) + } +} From 31ba33e34118bf2779b7646a47058bbb3f37920a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:27:20 +0800 Subject: [PATCH 2/6] fix: preserve doctor report on governance failure and cross-scope pending recovery --- Documentation/Reference/CLI.md | 5 ++-- Sources/CLI/JSONReports.swift | 4 +++- Sources/CLI/LifecycleCommands.swift | 31 +++++++++++++++++++++---- Tests/CLITests/ExecutableTests.swift | 6 +++++ Tests/CLITests/HostPluginCLITests.swift | 24 +++++++++++++++++++ 5 files changed, 63 insertions(+), 7 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 59e4c1d..ffcc02a 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -426,8 +426,9 @@ Completion lines identify the component and target after a successful apply. ## Host Plugins Add a `kind: hostPlugin` component to the selected scope's `agents.yaml` with a -name, explicit recipients, and either a `pluginId` or one bundle selected by -`source` and `path`. Set `enabled: false` to request disabled state. The default +name and either a `pluginId` (with exactly one explicit recipient in `agents`) +or one bundle selected by `source` and `path` (with one or more explicit +recipients in `agents`). Set `enabled: false` to request disabled state. The default is enabled. Core supports Codex, Claude Code, and Antigravity. Claude Code defaults to the selected agents scope, with an optional `claudeScope` of `user`, `project`, or `local`. diff --git a/Sources/CLI/JSONReports.swift b/Sources/CLI/JSONReports.swift index d8e71f6..2ebbe04 100644 --- a/Sources/CLI/JSONReports.swift +++ b/Sources/CLI/JSONReports.swift @@ -265,7 +265,8 @@ struct DoctorRoot: Encodable { init( root: String, scope: String, report: DoctorReport, instructions: InstructionDoctorReport, environment: RuntimeEnvironment, inventory: ScopeInspection? = nil, - policyChecks: [CheckItem] = [], governance: SkillGovernanceReport? = nil, ci: Bool = false + policyChecks: [CheckItem] = [], governance: SkillGovernanceReport? = nil, + governanceChecks: [CheckItem] = [], ci: Bool = false ) { self.root = root self.scope = scope @@ -275,6 +276,7 @@ struct DoctorRoot: Encodable { + (inventory.map { CheckItem.inventory($0, environment: environment) } ?? []) + policyChecks + (governance?.checks.map(CheckItem.init) ?? []) + + governanceChecks ok = !checks.contains { $0.status == "error" } if let budgets = governance?.skillBudgets, !budgets.isEmpty { skillBudgets = budgets.map(SkillBudgetItem.init) diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index 8596516..44535da 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -181,14 +181,37 @@ struct Doctor: ParsableCommand { let instructions = try InstructionOperations.doctor( scope: location.scope, environment: runtime) let inventory = try UpdateOperations.inspect(scope: location.scope, environment: runtime) + let pendingRecovery = + inventory.recovery.pending + || report.checks.contains { + ["pending-recovery", "unresolved-transaction"].contains($0.id) + } + || instructions.diagnostics.contains { + $0.kind == .pendingRecovery || $0.kind == .unresolvedTransaction + } let governance: SkillGovernanceReport? + let governanceChecks: [CheckItem] + if pendingRecovery { + governance = nil + governanceChecks = [] + } else { + do { + governance = try SkillGovernance.inspect( + scope: location.scope, agents: agents.recipients, environment: runtime) + governanceChecks = [] + } catch { + governance = nil + governanceChecks = [ + CheckItem( + kind: "governance", id: "governance-unavailable", status: "warning", + message: String(describing: error), path: nil) + ] + } + } let policyChecks: [CheckItem] if inventory.recovery.pending { - governance = nil policyChecks = [] } else { - governance = try SkillGovernance.inspect( - scope: location.scope, agents: agents.recipients, environment: runtime) do { let hasSelection = runtime.userOrganizationPolicy != nil @@ -237,7 +260,7 @@ struct Doctor: ParsableCommand { root: location.scope == .user ? environment.homeDirectory.path : project.path, scope: location.scope.rawValue, report: report, instructions: instructions, environment: runtime, inventory: inventory, policyChecks: policyChecks, - governance: governance, ci: ci)) + governance: governance, governanceChecks: governanceChecks, ci: ci)) } let report = DoctorOutput(roots: reports) if json { diff --git a/Tests/CLITests/ExecutableTests.swift b/Tests/CLITests/ExecutableTests.swift index 9ce58d9..e7ce3d9 100644 --- a/Tests/CLITests/ExecutableTests.swift +++ b/Tests/CLITests/ExecutableTests.swift @@ -257,6 +257,11 @@ struct ExecutableTests { try FileManager.default.createDirectory(at: state, withIntermediateDirectories: true) let journal = fixture.state("transaction.new", scope: "user") try Data("partial journal".utf8).write(to: journal) + let skill = fixture.home.appendingPathComponent(".codex/skills/demo/SKILL.md") + try FileManager.default.createDirectory( + at: skill.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("---\nname: demo\ndescription: Discoverable skill\n---\n\nBody\n".utf8) + .write(to: skill) let message = "Transaction recovery is pending; run 'agents install --scope user' to finish recovery." let human = try fixture.run(["doctor", "--root", fixture.source.path]) @@ -270,6 +275,7 @@ struct ExecutableTests { #expect(report["ok"] as? Bool == false) let roots = try #require(report["roots"] as? [[String: Any]]) let checks = try #require(roots.first?["checks"] as? [[String: String]]) + #expect(roots.first?["skillBudgets"] == nil) #expect( checks == [ [ diff --git a/Tests/CLITests/HostPluginCLITests.swift b/Tests/CLITests/HostPluginCLITests.swift index e9ca24b..585ad85 100644 --- a/Tests/CLITests/HostPluginCLITests.swift +++ b/Tests/CLITests/HostPluginCLITests.swift @@ -397,6 +397,30 @@ struct HostPluginCLITests { #expect(filteredRoot["skillBudgets"] == nil) } + @Test func doctorContinuesPolicyAuditWhenGovernanceDiscoveryFails() throws { + let fixture = try CLIFixture() + let result = try fixture.run( + ["doctor", "--ci", "--json", "--require-organization-policy", "--agent", "codex"], + environment: ["CODEX_HOME": "/dev/null"]) + #expect(result.status == 1 && result.stderr.isEmpty) + let report = try result.json() + #expect(report["ok"] as? Bool == false) + let root = try doctorRoot(report) + #expect(root["ok"] as? Bool == false && root["skillBudgets"] == nil) + let checks = try #require(root["checks"] as? [[String: Any]]) + let policy = try #require( + checks.first { + $0["kind"] as? String == "sourcePolicy" + && $0["id"] as? String == "missingOrganizationPolicy" + }) + #expect(policy["status"] as? String == "error") + let governance = try #require( + checks.first { + $0["kind"] as? String == "governance" && $0["id"] as? String == "governance-unavailable" + }) + #expect(governance["status"] as? String == "warning") + } + private func doctorRoot(_ report: [String: Any]) throws -> [String: Any] { try #require((report["roots"] as? [[String: Any]])?.first) } From 80af76abdee5b67927a1d2c7b87c88716713aef2 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:29:06 +0800 Subject: [PATCH 3/6] chore: set release version to 0.3.2 --- CHANGELOG.md | 4 ++-- Sources/CLI/EntryPoint.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7927c00..8b0c642 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,9 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased -## [0.4.0] - 2026-11-30 +## [0.3.2] - 2026-11-30 -Built on agents-tools/core 0.4.0. +Built on agents-tools/core 0.3.2. ### Added diff --git a/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index 68d5aef..4866106 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -9,7 +9,7 @@ import Foundation #endif enum BuildInfo { - static let version = "0.4.0" + static let version = "0.3.2" } struct Agents: ParsableCommand { From 0967429fb86cdfa3f8cec9883fcadc7e137f63a3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 30 Nov 2026 17:47:34 +0800 Subject: [PATCH 4/6] docs: document host plugin commands and release smoke check --- Documentation/Reference/Release.md | 7 ++++++- README.md | 8 +++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index dfe0671..0a20760 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -74,7 +74,12 @@ unset checked_commit checked_version verified_tag && checked_commit=$release_commit ``` -Lint must produce zero findings. Set the intended version explicitly. `agents` +Lint must produce zero findings. Before tagging, also run a read-only smoke +check of the built release binary against realistic user host configuration +(such as `.build/release-validation/release/agents plugins list --scope user --json` +and `.build/release-validation/release/agents doctor --scope user --json`) to +verify real-scale configuration parsing without mutating host state. Set the +intended version explicitly. `agents` uses unprefixed `X.Y.Z` tags, matching agents-tools/core. Before using the intended version, run the guard below once with a deliberately diff --git a/README.md b/README.md index e904a36..e99007d 100644 --- a/README.md +++ b/README.md @@ -115,6 +115,9 @@ agents components remove review --kind command agents import review.md --root /path/to/source --format claudeCommandV1 agents import review.md --root /path/to/source --format claudeCommandV1 --apply agents mcp test local-tools --binding token=TOOLS_TOKEN --json +agents plugins list --scope user --json +agents plugins sync --scope user +agents plugins sync --scope user --apply ``` Declarations live in `.agent/agents.yaml` for project scope or @@ -156,7 +159,10 @@ producer document and applies its canonical intent only with `--apply`. `mcp test` explicitly starts or contacts one selected managed MCP server and discovers its tools. Runtime bindings use repeated `--binding NAME=ENV_VAR` mappings on apply or test commands. Values are read only when Core requests that -symbolic binding and are not included in reports. See the [CLI reference](Documentation/Reference/CLI.md) +symbolic binding and are not included in reports. `plugins list` compares +declared `kind: hostPlugin` entries against observed Codex, Claude Code, and +Antigravity plugin state without running host commands; `plugins sync` previews +reconciliation and applies changes only with `--apply`. See the [CLI reference](Documentation/Reference/CLI.md) for supported profiles, selection options and report schemas. ## Requirements From c8d8f6aec8a924fb30236e0b410eb8dcbdc118e9 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 1 Dec 2026 11:46:27 +0800 Subject: [PATCH 5/6] build: depend on agents-tools/core 0.3.2 --- Documentation/Reference/CLI.md | 2 +- Package.resolved | 6 +++--- Package.swift | 2 +- README.md | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index ffcc02a..0622cb6 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -982,7 +982,7 @@ under `--ci`. Doctor skips governance when transaction recovery is pending. | User | `~/.agents/agents.yaml` | `~/.agents/agents.resolved` | `~/.agents/cache/` | A project commits its declaration and lock; the cache stays local. `agents.yaml` -uses the [manifest format](https://github.com/agents-tools/core/blob/25d965fa18465f60341ba81bff4a511766d7659b/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/0.3.2/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Package.resolved b/Package.resolved index c4214d4..7acf031 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "8da077cf245d6fbebc8831b63b38cc6354f159c9999e2a161197b12048635975", + "originHash" : "6fd73f7f16b0509120688d175f714f88e76c59aaeee6284c392d30986c015fc7", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "ce6640adeb53ce0152134547938a6e13472e28b5", - "version" : "0.3.1" + "revision" : "c6365a62374d42339a4384444eb42c252379cfff", + "version" : "0.3.2" } }, { diff --git a/Package.swift b/Package.swift index 81edb7d..a35317e 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - "0.3.1"..<"0.4.0"), + "0.3.2"..<"0.4.0"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index e99007d..fae2e95 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ agents plugins sync --scope user --apply ``` Declarations live in `.agent/agents.yaml` for project scope or -`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/0.3.1/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/0.3.2/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 961f20cfd9552340bc589027b82a1925eab9fdfc Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:03:28 +0800 Subject: [PATCH 6/6] test: use unreadable skills directory for cross-platform governance failure check --- Tests/CLITests/HostPluginCLITests.swift | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/Tests/CLITests/HostPluginCLITests.swift b/Tests/CLITests/HostPluginCLITests.swift index 585ad85..bbcd12e 100644 --- a/Tests/CLITests/HostPluginCLITests.swift +++ b/Tests/CLITests/HostPluginCLITests.swift @@ -399,9 +399,14 @@ struct HostPluginCLITests { @Test func doctorContinuesPolicyAuditWhenGovernanceDiscoveryFails() throws { let fixture = try CLIFixture() + let skills = fixture.home.appendingPathComponent(".codex/skills") + try FileManager.default.createDirectory(at: skills, withIntermediateDirectories: true) + try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: skills.path) + defer { + try? FileManager.default.setAttributes([.posixPermissions: 0o700], ofItemAtPath: skills.path) + } let result = try fixture.run( - ["doctor", "--ci", "--json", "--require-organization-policy", "--agent", "codex"], - environment: ["CODEX_HOME": "/dev/null"]) + ["doctor", "--ci", "--json", "--require-organization-policy", "--agent", "codex"]) #expect(result.status == 1 && result.stderr.isEmpty) let report = try result.json() #expect(report["ok"] as? Bool == false)