diff --git a/.agent/agents.json b/.agent/agents.json deleted file mode 100644 index 5c68742..0000000 --- a/.agent/agents.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "instructions": { - "agents": ["claude-code", "codex"], - "sections": [ - "guide", - "agents-tools:shared/swift-package-route", - "agents-tools:shared/swift-package-tests" - ] - }, - "sources": { - "agents-tools": { - "branch": "master", - "git": "github.com/agents-tools/.github", - "path": ".agent" - } - } -} diff --git a/.agent/agents.resolved b/.agent/agents.resolved index 3fd02bf..a183d50 100644 --- a/.agent/agents.resolved +++ b/.agent/agents.resolved @@ -1,47 +1 @@ -{ - "instructions": { - "chatgpt": {}, - "sections": [ - { - "hash": "sha256:5621e384e329921041b3370990d001da255847cee4bd0327a4f5e5634221ca0a", - "name": "guide", - "path": ".agent/instructions/guide.md", - "source": "." - }, - { - "hash": "sha256:a45b15d662eecec4b252fa2e35a608bab0ee137fae525669097f45d0f8c3f39d", - "name": "shared/swift-package-route", - "path": ".agent/instructions/shared/swift-package-route.md", - "revision": "fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea", - "source": "github.com/agents-tools/.github" - }, - { - "hash": "sha256:5d9f40d101938d2805482b9a147397bc07e9c3c9223cfe040f0905cb6c746825", - "name": "shared/swift-package-tests", - "path": ".agent/instructions/shared/swift-package-tests.md", - "revision": "fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea", - "source": "github.com/agents-tools/.github" - } - ], - "targets": { - "AGENTS.md": { - "agents": ["claude-code", "codex"], - "blockHash": "sha256:9e6506e733a03fca717725c229fe8d7e2e599ca96a77555c46086f159c8384ba", - "created": false, - "headingOffset": 0 - } - } - }, - "skills": {}, - "sources": { - "github.com/agents-tools/.github": { - "kind": "git", - "path": ".agent", - "requirement": { - "branch": "master" - }, - "url": "https://github.com/agents-tools/.github" - } - }, - "version": 1 -} +{"components":{"sha256:754407554f06d2e1ae23a32c4e2bc39d16781cf468fed1a48e35def4f0836426":{"chatGPT":false,"conditions":[{}],"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","kind":"instructions","name":"shared/swift-package-route","payload":{"kind":"object","object":{"name":{"kind":"string","text":"shared/swift-package-route"},"native":{"kind":"object","object":{}},"sourceHash":{"kind":"string","text":"sha256:a45b15d662eecec4b252fa2e35a608bab0ee137fae525669097f45d0f8c3f39d"}}},"recipients":["claude-code","codex"],"resources":["sha256:cb6aea4e7350afe57cdb7729e9b9daabf33eae2286d59f5314a0ae605f29c9f3"],"revision":"fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea","root":".","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"},"sha256:c91e014fcb3b3707906b30d7879b9ba3db884bfa9ed19c7133d4d38f25e3c407":{"chatGPT":false,"conditions":[{}],"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","kind":"instructions","name":"guide","payload":{"kind":"object","object":{"name":{"kind":"string","text":"guide"},"native":{"kind":"object","object":{}},"sourceHash":{"kind":"string","text":"sha256:5621e384e329921041b3370990d001da255847cee4bd0327a4f5e5634221ca0a"}}},"recipients":["claude-code","codex"],"resources":["sha256:63c32ff63d3635e0f65cb6b8ba472a4c753118cda926269ff5f513b1db35b340"],"root":".","source":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8"},"sha256:e4a73605a9830d1c8804aebf5558b8c0c2af26fa405ce5b6591d91c943db5d16":{"chatGPT":false,"conditions":[{}],"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","kind":"instructions","name":"shared/swift-package-tests","payload":{"kind":"object","object":{"name":{"kind":"string","text":"shared/swift-package-tests"},"native":{"kind":"object","object":{}},"sourceHash":{"kind":"string","text":"sha256:5d9f40d101938d2805482b9a147397bc07e9c3c9223cfe040f0905cb6c746825"}}},"recipients":["claude-code","codex"],"resources":["sha256:3e6e83f98fceb7ee2f89a4e7e6eac3a396d02b1c8341f6ec516e1f230e2c2a11"],"revision":"fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea","root":".","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"}},"contentObjects":{"sha256:5621e384e329921041b3370990d001da255847cee4bd0327a4f5e5634221ca0a":"LS0tCmRlc2NyaXB0aW9uOiBLZWVwIHRoZSBhZ2VudHMgQ0xJIGEgY29tbWFuZCBsYXllciBvdmVyIGNvcmUsIHdpdGggaXRzIG93biBzY2hlbWFzLCBjb250cmFjdCBkb2N1bWVudCBhbmQgdmVyaWZpZWQgQ0kgY29udGV4dHMuCi0tLQojIGNsaSBBZ2VudCBHdWlkZQoKIyMgT3duZXJzaGlwCgotIEtlZXAgY29tbWFuZCBwYXJzaW5nLCB0ZXJtaW5hbCBvdXRwdXQsIGV4aXQgY29kZXMgYW5kIEpTT04gc2NoZW1hcyBoZXJlLCBhbmQKICBrZWVwIENMSSBzY2hlbWEgdHlwZXMgaW5kZXBlbmRlbnQgb2YgY29yZSdzIGVuY29kZWQgcmVwcmVzZW50YXRpb25zLgotIEtlZXAgc291cmNlIHJlc29sdXRpb24sIGRlY2xhcmF0aW9ucywgbG9ja3MsIHJlY292ZXJ5LCBkaXNjb3ZlcnkgYW5kIHNraWxsCiAgbGlmZWN5Y2xlIGJlaGF2aW9yIGluIGFnZW50cy10b29scy9jb3JlOyB1c2UgaXRzIHB1YmxpYyBBUElzLgotIFVwZGF0ZSBgRG9jdW1lbnRhdGlvbi9SZWZlcmVuY2UvQ0xJLm1kYCwgdGhlIHNoaXBwZWQgY29tbWFuZCBjb250cmFjdCwgd2l0aAogIGV2ZXJ5IGNvbW1hbmQgY2hhbmdlLiBUaGUgZXhlY3V0YWJsZSB2ZXJzaW9uIGxpdmVzIGluCiAgYFNvdXJjZXMvQ0xJL0VudHJ5UG9pbnQuc3dpZnRgLgoKIyMgV29ya2Zsb3dzIGFuZCBBc3NldHMKCi0gRm9yIHdvcmtmbG93IGNoYW5nZXMsIHJ1biBgYWN0aW9ubGludGAgb24gZXZlcnkgd29ya2Zsb3cuIFZlcmlmeSB0aGUgcmVxdWlyZWQKICBjaGVja3Mgb24gYSByZWFsIGNhbmRpZGF0ZSBydW4gYmVmb3JlIGNoYW5naW5nIHJlcXVpcmVkLWNoZWNrIHNldHRpbmdzLgotIFRoZSBkZW1vIGpvYiByZS1yZWNvcmRzIGByZWNvcmRpbmcuanNvbmAgYW5kIHVwbG9hZHMgaXQgb24gZHJpZnQuIFJlbmRlciBhbmQKICBjaGVjayB0ZXJtaW5hbCBTVkdzIGFuZCB0aGUgc29jaWFsIHByZXZpZXcgbG9jYWxseSB3aXRoIHRoZQogIGdpdGh1Yi1yZWFkbWUtZGVzaWduIHRvb2xjaGFpbiBhZ2FpbnN0IGBhZ2VudHMtdG9vbHMvLmdpdGh1YmAncyBERVNJR04sIGZvbnRzCiAgYW5kIGNhdGFsb2cuCg=="},"deployments":[{"created":false,"expectedHash":"sha256:9e6506e733a03fca717725c229fe8d7e2e599ca96a77555c46086f159c8384ba","headingOffset":0,"id":"instructions:AGENTS.md","owners":["sha256:c91e014fcb3b3707906b30d7879b9ba3db884bfa9ed19c7133d4d38f25e3c407","sha256:754407554f06d2e1ae23a32c4e2bc39d16781cf468fed1a48e35def4f0836426","sha256:e4a73605a9830d1c8804aebf5558b8c0c2af26fa405ce5b6591d91c943db5d16"],"ownership":"generated","recipients":["claude-code","codex"],"route":"agents/instructions@1","target":{"kind":"registered","path":"AGENTS.md","root":"project"}}],"groups":[],"lowerings":[{"artifacts":[{"hash":"sha256:9e6506e733a03fca717725c229fe8d7e2e599ca96a77555c46086f159c8384ba","kind":"file","name":"instructions:AGENTS.md"}],"deployments":["instructions:AGENTS.md"],"format":"agents/instructions@1","id":"instructions:AGENTS.md","inputs":["sha256:c91e014fcb3b3707906b30d7879b9ba3db884bfa9ed19c7133d4d38f25e3c407","sha256:754407554f06d2e1ae23a32c4e2bc39d16781cf468fed1a48e35def4f0836426","sha256:e4a73605a9830d1c8804aebf5558b8c0c2af26fa405ce5b6591d91c943db5d16"],"layout":{"kind":"object","object":{"headingOffset":{"integer":0,"kind":"integer"},"name":{"kind":"string","text":"instructions:AGENTS.md"}}},"platform":"macos","resources":["sha256:63c32ff63d3635e0f65cb6b8ba472a4c753118cda926269ff5f513b1db35b340","sha256:cb6aea4e7350afe57cdb7729e9b9daabf33eae2286d59f5314a0ae605f29c9f3","sha256:3e6e83f98fceb7ee2f89a4e7e6eac3a396d02b1c8341f6ec516e1f230e2c2a11"]}],"occurrences":[{"component":"sha256:c91e014fcb3b3707906b30d7879b9ba3db884bfa9ed19c7133d4d38f25e3c407","condition":{},"consumerEditable":true,"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","dependencies":["sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8"],"id":0,"manifestPath":".agent/agents.yaml","recipients":["claude-code","codex"]},{"component":"sha256:754407554f06d2e1ae23a32c4e2bc39d16781cf468fed1a48e35def4f0836426","condition":{},"consumerEditable":true,"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","dependencies":["sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"],"id":1,"manifestPath":".agent/agents.yaml","recipients":["claude-code","codex"]},{"component":"sha256:e4a73605a9830d1c8804aebf5558b8c0c2af26fa405ce5b6591d91c943db5d16","condition":{},"consumerEditable":true,"declaringSource":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","dependencies":["sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"],"id":2,"manifestPath":".agent/agents.yaml","recipients":["claude-code","codex"]}],"resources":{"sha256:3e6e83f98fceb7ee2f89a4e7e6eac3a396d02b1c8341f6ec516e1f230e2c2a11":{"entries":[{"byteCount":421,"executable":false,"kind":"file","path":"."}],"hash":"sha256:5d9f40d101938d2805482b9a147397bc07e9c3c9223cfe040f0905cb6c746825","kind":"git","path":".agent/instructions/shared/swift-package-tests.md","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6","support":[]},"sha256:63c32ff63d3635e0f65cb6b8ba472a4c753118cda926269ff5f513b1db35b340":{"entries":[{"byteCount":1042,"executable":false,"kind":"file","object":"sha256:5621e384e329921041b3370990d001da255847cee4bd0327a4f5e5634221ca0a","path":"."}],"hash":"sha256:5621e384e329921041b3370990d001da255847cee4bd0327a4f5e5634221ca0a","kind":"embedded","path":".agent/instructions/guide.md","source":"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8","support":[]},"sha256:cb6aea4e7350afe57cdb7729e9b9daabf33eae2286d59f5314a0ae605f29c9f3":{"entries":[{"byteCount":1077,"executable":false,"kind":"file","path":"."}],"hash":"sha256:a45b15d662eecec4b252fa2e35a608bab0ee137fae525669097f45d0f8c3f39d","kind":"git","path":".agent/instructions/shared/swift-package-route.md","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6","support":[]}},"sourceUses":[{"requirement":{"branch":"master"},"root":".agent","source":"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6"}],"sources":{"sha256:106e5eaca24fac766d77fa1b5b2cad5b4fdf537929ed086f49e2142f702329a6":{"kind":"git","revision":"fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea","transport":"https://github.com/agents-tools/.github"},"sha256:d20f3fcaba358dcbae462caf58d6393127b61d91f2ba3197b0f84a019dd0e9d8":{"kind":"local","location":{"kind":"registered","path":".","root":"project"},"revision":"live"}},"version":2} diff --git a/.agent/agents.yaml b/.agent/agents.yaml new file mode 100644 index 0000000..2799bdd --- /dev/null +++ b/.agent/agents.yaml @@ -0,0 +1,13 @@ +version: 1 +sources: + agents-tools: + url: https://github.com/agents-tools/.github + requirement: {branch: master} + subpath: .agent +components: + - kind: instructions + agents: [claude-code, codex] + sections: + - {name: guide} + - {name: shared/swift-package-route, source: agents-tools} + - {name: shared/swift-package-tests, source: agents-tools} diff --git a/.github/ci/linux-tests.Dockerfile b/.github/ci/linux-tests.Dockerfile new file mode 100644 index 0000000..e7506cc --- /dev/null +++ b/.github/ci/linux-tests.Dockerfile @@ -0,0 +1,13 @@ +ARG SWIFT_IMAGE +FROM ${SWIFT_IMAGE} + +ARG TEST_UID +ARG TEST_GID +RUN apt-get update \ + && apt-get install -y --no-install-recommends libsqlite3-dev \ + && rm -rf /var/lib/apt/lists/* \ + && (getent group "$TEST_GID" || groupadd --gid "$TEST_GID" test-runner) \ + && (getent passwd "$TEST_UID" || useradd --create-home --uid "$TEST_UID" --gid "$TEST_GID" test-runner) + +USER ${TEST_UID}:${TEST_GID} +WORKDIR /workspace diff --git a/.github/ci/test-linux.sh b/.github/ci/test-linux.sh new file mode 100644 index 0000000..a2128e7 --- /dev/null +++ b/.github/ci/test-linux.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail + +root=$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd) +image=$(docker build --quiet \ + --file "$root/.github/ci/linux-tests.Dockerfile" \ + --build-arg "SWIFT_IMAGE=$1" \ + --build-arg "TEST_UID=$(id -u)" \ + --build-arg "TEST_GID=$(id -g)" \ + "$root/.github/ci") + +docker run --rm --init --volume "$root:/workspace" \ + --env HOME=/tmp --env GIT_CONFIG_NOSYSTEM=1 --env GIT_CONFIG_GLOBAL=/dev/null \ + "$image" swift test --scratch-path .build/linux --jobs 2 diff --git a/.github/swift-package.json b/.github/swift-package.json index 35a9e8a..4ffd88a 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -2,5 +2,12 @@ "compilers": [ {"name": "macos-26-xcode-26.6", "runner": "macos-26", "xcode": "26.6"} ], - "demo": {"product": "agents"} + "demo": {"product": "agents"}, + "commands": [ + { + "name": "linux-swift-6.4.1", + "runner": "ubuntu-24.04", + "run": "bash .github/ci/test-linux.sh swift:6.4.1-noble@sha256:6304481cf2717966b7ba175162e397ea2f2cc3161909f2b2a5cf40036079a0f7" + } + ] } diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7907540..bb0d55f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,4 +19,4 @@ jobs: permissions: contents: read actions: read - uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@bb0a8c8c39827a364b9d3cbf4069754e7d975586 + uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@314a41dcae51ff835a9418acfde6542d970b7f16 diff --git a/.github/workflows/source-policy.yml b/.github/workflows/source-policy.yml index b6a1735..6a3c8c5 100644 --- a/.github/workflows/source-policy.yml +++ b/.github/workflows/source-policy.yml @@ -16,7 +16,7 @@ concurrency: jobs: policy: - uses: agents-tools/github-workflows/.github/workflows/policy.yml@bb0a8c8c39827a364b9d3cbf4069754e7d975586 + uses: agents-tools/github-workflows/.github/workflows/policy.yml@314a41dcae51ff835a9418acfde6542d970b7f16 with: allow-terms: | ChatGPT diff --git a/.gitignore b/.gitignore index a2e2dbd..af598d1 100644 --- a/.gitignore +++ b/.gitignore @@ -4,5 +4,5 @@ .claude/ /.agent/* !/.agent/instructions/ -!/.agent/agents.json +!/.agent/agents.yaml !/.agent/agents.resolved diff --git a/CHANGELOG.md b/CHANGELOG.md index 3401fdb..475c222 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,28 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## [0.3.1] - 2026-11-29 + +### Added + +- Inspect available components, add exported groups and import supported native + configuration with a preview. Review changes with `agents update` and apply + them with `agents update --apply`. +- Inspect the complete declaration and its diagnostics with + `agents manifest dump --json`. See the [report contract](Documentation/Reference/ManifestDump.md). +- Search the MCP registry, inspect server details and test a configured connection. +- Export and import portable configuration bundles. Publish packages to a marketplace, + inspect dependencies and review locked deployments and upgrades. +- Inspect allowed package sources and credential availability, manage the download cache, + audit prompt content and export local edits as patches for their producers. +- Review package lifecycle actions and manage project trust. Install selected Antigravity + instruction rules at user or project scope. + +### Changed + +- Project declarations use `.agent/agents.yaml` and user declarations use + `~/.agents/agents.yaml`. Resolved configuration uses the version 2 JSON ledger. + ## [0.2.0] - 2026-10-27 Built on agents-tools/core 0.2.0. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 112e264..da15901 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,8 +7,9 @@ Use a task worktree, signed Conventional Commits, and the [development checks](README.md#development). Push and merge require maintainer authorization. -Build with Swift 6.3 or later on macOS 15 or later. Shared CI compiles and tests -only with Xcode 26.6 on `macos-26`. +Source builds support macOS and Linux; [Package.swift](Package.swift) defines the +minimum toolchain and macOS versions. Shared CI compiles and tests with Xcode +26.6 on `macos-26` and a pinned Swift 6.4.1 Noble container image for Linux. Package validation is configured in [.github/swift-package.json](.github/swift-package.json) and runs through [agents-tools/github-workflows](https://github.com/agents-tools/github-workflows#readme). diff --git a/Documentation/Decisions/FrontEnds.md b/Documentation/Decisions/FrontEnds.md new file mode 100644 index 0000000..10ede77 --- /dev/null +++ b/Documentation/Decisions/FrontEnds.md @@ -0,0 +1,83 @@ +# Front Ends + +## Status + +Accepted + +## Context + +Core owns sources, declarations, locks, discovery, installation and recovery. +The `agents` CLI and the skills-only `skill` CLI already share core and its +state. A macOS GUI will manage everything the CLI manages. Comparable desktop +apps keep their own databases, so their view of intent and the files on disk +can disagree with each other and with any CLI. + +## Decision + +- **Core owns behavior.** The `agents` CLI, the macOS GUI and the `skill` CLI + are front ends over core and one shared state. Every GUI operation has a CLI + command. The GUI links core directly, and the GUI and CLI release together + at the same version. +- **No GUI-private state.** Business facts live in `agents.yaml`, the lock and + core-managed state; the GUI keeps only interface preferences. Presets and + collections are named groups in the manifest. Moving a setup to another + machine means syncing `agents.yaml` and the lock and running + `agents install`. +- **Configuration application.** The GUI shows the concrete configuration + changes and targets; one confirmation applies them through core. Explicit + modifying CLI commands express the same intent. External automation invokes + those commands within its supplied scope. +- **MCP connection tests.** A separate optional action checks the selected + configuration by initializing the protocol and discovering tools. A local + stdio test starts its displayed command. The result describes that test, + independently of configuration application and the native client's runtime + trust, authentication and tool-call permissions. +- **Previews bind to apply.** The GUI uses core's prepare and apply. If the + manifest or targets change during a preview, apply re-checks and refreshes + the plan. +- **Manifest editing.** The GUI edits manifest constructs that core can edit + exactly and shows the rest read-only, with a way to open the file in an + editor. +- **Updates.** The GUI checks and notifies, and applies on request. +- **On-device assistance.** Where Apple's on-device model is available, the + GUI uses Foundation Models to explain a skill, translate its description, + summarize an update and explain configuration changes. These + features are hidden when the model is unavailable and can be turned off. +- **The `skill` CLI** remains the skills-only entry point over the same core + and state, released on the same core version. +- **The GUI** lives in its own repository in the agents-tools organization and + ships as a notarized Homebrew cask. +- **Usage guidance.** A skill published by the agents-tools organization + teaches agents and people to use `agents` and write `agents.yaml`. + +## Consequences + +- Every capability lands in core before a front end exposes it. +- The CLI's machine-readable output and core's API are the contracts the GUI + and `skill` depend on; incompatible changes follow the family versioning + policy for each consumer. +- The GUI watches the manifest, lock and targets and refreshes from core + diagnostics rather than caching status. +- Foundation Models features exist only in the GUI, because the CLI also runs + on Linux. + +## Alternatives Considered + +- **A GUI that shells out to the CLI.** Progress, cancellation and file + watching would be limited to what text output carries. +- **A GUI database for intent.** The CLI could not read it, and state would + diverge. +- **Retire the `skill` CLI.** Skills-only installers remain widely used, and + `skill` serves them at little cost while it carries no logic of its own. +- **A cloud LLM client in the GUI.** Adds provider keys, cost and outbound + data, and turns a manager into a coding assistant. +- **Automatic update apply.** Deferred; checks and one-step apply keep every + change reviewed. + +## Related Documentation + +- Accepted by the repository owner (showxu) on 2026-10-28. +- Product scope: [Product Scope](ProductScope.md) +- Configuration application clarified by the owner on 2026-11-06: + [Configuration Application](https://github.com/agents-tools/core/blob/19be46f3c38efbd32bb95ae33649d1b141b7efe6/Documentation/Decisions/ConfigurationApplication.md) +- Current architecture: [Architecture](../Architecture/README.md) diff --git a/Documentation/Decisions/ProductScope.md b/Documentation/Decisions/ProductScope.md new file mode 100644 index 0000000..564ff50 --- /dev/null +++ b/Documentation/Decisions/ProductScope.md @@ -0,0 +1,64 @@ +# Product Scope + +## Status + +Accepted + +## Context + +`agents` manages skills and instructions for coding agents. Comparable tools +each cover part of the space: Microsoft APM is the most complete package +manager for agent configuration, rulesync spans the most components and +targets, npx skills is the most used skills installer, and several desktop +apps manage skills. The next stage turns `agents` into a full management CLI +with a macOS GUI. + +## Decision + +- **Independent tool.** `agents` has its own manifest and engine. It neither + adopts `apm.yml` as its manifest nor delegates to another manager. + Configurations from APM, rulesync and npx skills are imported one way. +- **Scope.** Everything APM can do for the supported agents, plus the + components rulesync covers beyond it, such as permissions and ignore rules, + each covered or exceeded. Exclusions are explicit: agents beyond the + supported set, a built-in general-purpose LLM client, a web GUI, desktop GUIs + on other platforms, telemetry by default and a Windows CLI. +- **Supported agents.** Claude Code, Codex, Cursor, Gemini CLI and OpenCode, at + their current stable releases. Support claims are verified against those + clients, and `doctor` reports an installed client older than the verified + release. +- **Platforms.** The CLI runs on macOS 15, 26 and 27 and on Linux. The GUI runs + on macOS. +- **Configuration management.** Users inspect and apply concrete configuration + changes. MCP connection testing is an optional explicit action; the consuming + agent owns runtime trust, authentication and tool-call permissions. +- **Conventions.** Content keeps its ecosystem formats: a skill is a directory + with `SKILL.md`, and instructions are Markdown with front matter. A + repository laid out by those conventions is usable as a source without an + `agents.yaml`. + +## Consequences + +- Core and the CLI build and test on Linux in CI. +- Each scope item is tracked against the comparable tools' capabilities, and + each exclusion keeps its reason. +- New components and agents enter through core's capability registry and + client verification. + +## Alternatives Considered + +- **Read and write `apm.yml` as the manifest.** Couples the model to APM's + package semantics and leaves two managers owning the same outputs. +- **Build on the APM CLI.** Adds a Python runtime and limits the product to + APM's behavior. +- **Match upstream agent counts.** Breadth across dozens of agents would come + at the cost of verified depth on the agents in use. + +## Related Documentation + +- Accepted by the repository owner (showxu) on 2026-10-28. +- Front ends over core: [Front Ends](FrontEnds.md) +- Manifest and components: [core decisions](https://github.com/agents-tools/core/tree/master/Documentation/Decisions) +- Configuration application clarified by the owner on 2026-11-06: + [Configuration Application](https://github.com/agents-tools/core/blob/19be46f3c38efbd32bb95ae33649d1b141b7efe6/Documentation/Decisions/ConfigurationApplication.md) +- Current commands: [CLI reference](../Reference/CLI.md) diff --git a/Documentation/Decisions/README.md b/Documentation/Decisions/README.md index d28897d..02a013e 100644 --- a/Documentation/Decisions/README.md +++ b/Documentation/Decisions/README.md @@ -2,6 +2,12 @@ This directory holds durable decision records for `agents-tools/cli`. +## Records + +- `ProductScope.md`: independent tool, scope, supported agents, platforms and + content conventions +- `FrontEnds.md`: CLI, GUI and `skill` as front ends over core and shared state + ## Placement - Use this directory for accepted decisions and the rationale behind them. diff --git a/Documentation/README.md b/Documentation/README.md index 742f91c..99be2d5 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -12,8 +12,11 @@ This directory indexes repository-native documentation for `agents-tools/cli`. - [Archive](Archive/README.md): retired or superseded material kept for record - [CLI reference](Reference/CLI.md): shipped commands, options, output, errors, state locations, and JSON contracts. -- [JSON schemas](Reference/Schemas/): machine-readable schemas for list, - update previews, watch status and diffs, installation, and doctor. +- [Manifest dump](Reference/ManifestDump.md): producer-owned YAML manifest JSON contract + exposed by `agents manifest dump --json`. +- [JSON schemas](Reference/Schemas/): machine-readable schemas for component, + skill and instruction lists, update previews, watch status and diffs, + installation, doctor, import previews and explicit MCP tests. - [Release checklist](Reference/Release.md): prepare and verify release commits, publish signed tags, and validate the Homebrew formula. - [Terminal demo maintenance](Reference/TerminalDemo.md): review CI recording diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index fb7dadf..1db688a 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -1,8 +1,10 @@ # CLI Reference -`agents` manages declared skills and instructions. Resolution, installation, +`agents` manages declared agent components. Resolution, installation, state, and recovery operations use `AgentsCore`, `AgentsSkills`, and -`AgentsInstructions`; top-level updates use `AgentsUpdates`. +`AgentsInstructions`. Combined lifecycle, content audit, component inspection, +import and MCP tests use `AgentsUpdates`. `AgentsManifest` owns declaration +parsing and editing, and the manifest dump contract. ## Commands @@ -25,19 +27,69 @@ agents watch status [--json] [--scope project|user] agents watch diff [name] [--kind skill|instructions|artifact] [--json] [--scope project|user] agents watch seen [--revision ] [--scope project|user] agents watch remove [--scope project|user] -agents install [--json] -agents update [--apply | --json] -agents doctor [--root …] [--json] +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 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 ] +agents bundle plugin --target [--marketplace ] [--category ] [--output ] [--reviewed-digest ] +agents bundle export --name --package-version --component … [--dependency ]… [--scope ] +agents bundle inspect +agents bundle import --agent … [--component ] [--scope ] [--json | --apply] +agents auth check --source [--scope project|user] [--validate] [--json] +agents auth check --host [--json] +agents auth export --source [--scope project|user] +agents cache info [--json] +agents cache clean [--apply] [--json] +agents cache prune [--days ] [--apply] [--json] +agents marketplace publish (--directory | --catalog ) [--summary ] [--scope ] +agents marketplace stage --directory [--summary ] +agents marketplace register (--directory | --index | --git [--ref ] [--subpath ]) [--scope ] +agents marketplace list [--scope ] +agents marketplace unregister [--scope ] +agents marketplace search [] [--scope ] +agents marketplace verify [--scope ] +agents marketplace resolve [ [] [--alias ]] [--json] [--scope ] +agents marketplace install (--agent … [--component … | --member …] | --metadata-only) [] [--alias ] [--replace] [--binding NAME=ENV_VAR] [--lock-only] [--json | --apply] [--scope ] +agents marketplace lock [--scope ] [--json | --apply] +agents marketplace deploy [--scope ] [--replace] [--binding NAME=ENV_VAR] [--json | --apply] +agents marketplace installed [--scope ] +agents marketplace deps [--scope ] +agents marketplace why [--scope ] +agents marketplace outdated [] [--scope ] +agents marketplace upgrade [] [--agent … --member …] [--binding NAME=ENV_VAR] [--scope ] [--lock-only] [--json | --apply] +agents marketplace remove [--binding NAME=ENV_VAR] [--scope ] [--lock-only] [--json | --apply] +agents mcp search [] [--registry ] [--limit ] [--cursor ] [--all-versions] [--json] +agents mcp show [--server-version ] [--registry ] [--json] +agents mcp add --name --agent [--choice ] [--server-version ] [--input INPUT=ENV_VAR] [--scope project|user] [--apply] +agents mcp test [--kind mcpServer] [--identity ] [--occurrence ] [--binding NAME=ENV_VAR] [--json] [--scope project|user] +agents manifest dump --json [--scope project|user] +agents lifecycle list [--scope project|user] [--json] +agents lifecycle validate [--scope project|user] [--json] +agents lifecycle init [--scope project|user] [--force] [--apply [--reviewed-digest [--reviewed-original-digest ]]] [--json] +agents lifecycle test [] [--scope project|user] [--execute] [--json] +agents lifecycle trust [--apply [--reviewed-digest --reviewed-root --reviewed-revision ]] [--json] +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 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`, and each command's `--help` describe their options. +`agents watch --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` prints `agents X.Y.Z` and is available only on the root command; the version constant lives in `Sources/CLI/EntryPoint.swift`. -Root overview: "Manage agent skills and instructions from declared sources." +Root overview: "Manage agent components from declared sources." Root help includes: ```text @@ -55,20 +107,20 @@ Examples: | Option | Meaning | Commands | | --- | --- | --- | -| `--scope project\|user` | Where state lives: project (./.agent) or user (~/.agents). Default: project. | All lifecycle and read commands except `instructions export`; `init` uses the current directory | -| `--agent ` | Agent to install for: codex, claude-code, cursor, gemini-cli or opencode. 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 or opencode. Repeat for several. Default: all recipients. | `skills list`, `skills remove`, `doctor` | -| `--agent ` | Set the scope's entire instruction section list recipients. Repeat for several. Default: recorded instruction agents, else declaration agents, else codex and claude-code. | `instructions add`, `instructions remove`, `instructions update` | +| `--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 ` | 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` | +| `--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. | -Agents are `codex`, `claude-code`, `cursor`, `gemini-cli`, and `opencode`. -For instruction recipients, Cursor supports project scope only. ChatGPT is a -named render target, not a `--agent` value. Core also accepts `claude` and +Skill and instruction recipients are `codex`, `claude-code`, `cursor`, +`gemini-cli`, `opencode`, and `antigravity`. Cursor instructions use +project scope. ChatGPT is a named render target. Core also accepts `claude` and `gemini` as input aliases. Output uses canonical IDs. On skill add, omitted recipients use the agents already recorded for the skill or source, then declaration defaults (initially Codex and Claude Code). On skill list, skill @@ -88,6 +140,57 @@ the lock. Top-level update and install accept no recipient or mode override. change directory for project operations or use doctor's `--root` for auditing. Unsupported options are usage errors. +## Package Lifecycle Actions + +`lifecycle list` shows action sources, events, order and eligibility. +`lifecycle validate` reports declaration diagnostics with their source and +field. Both are read-only. Project scope includes administrator, user and +current project sources. User scope includes administrator and user sources. + +`lifecycle init` reviews starter events in an existing `agents.yaml` for the +selected scope. Pass `--apply` to save them and `--force` to replace an existing +lifecycle block. For a separate review, pass its document digest with +`--reviewed-digest`. A reviewed replacement also requires the preview's +`originalDigest` as `--reviewed-original-digest`. A scaffold save grants no trust. + +Project actions require trust for their exact lifecycle declaration and +physical project root. Run `lifecycle trust` to review the authored actions, +then `lifecycle trust --apply` to confirm at a terminal. For noninteractive +approval, pass the review's `digest`, `rootID` and `revision` as +`--reviewed-digest`, `--reviewed-root` and `--reviewed-revision`. Shell actions +run with your access and can invoke mutable checkout files outside the digest. +`lifecycle trusted` lists stored grants, including absent paths. Revoke any +grant with `lifecycle untrust --root-id `, or use its path when unique. + +`lifecycle test` simulates `post-install` by default. Select any event shown +below. `--execute` runs eligible actions from that review and waits for their +results. A failed or withheld explicit execution exits nonzero. Validation +errors also exit nonzero. `APM_NO_SCRIPTS=1` withholds action starts. + +| Package operation | Events | +| --- | --- | +| `install`, applied bundle import and marketplace install or deploy | `pre-install`, `post-install` | +| Applied `update`, `skills update`, `marketplace upgrade`, `marketplace lock` | `pre-update`, `post-update` | +| `skills remove`, `instructions remove`, `components remove`, applied `marketplace remove` | `pre-uninstall`, `post-uninstall` | +| Applied `instructions update` | `pre-compile` | + +A marketplace operation with `--lock-only` uses that command's own events. +Previews, inspection and exports run no actions. A package operation +reports action failures as advisory results and uses its package outcome for +the exit status. A failed package apply reports which actions already started. +Recovery before a review can retry preparation. A submitted review has one +attempt. + +Lifecycle JSON reports carry `schemaVersion: 1` and a `kind` for the command. +Action entries use zero-based indices within each source event. Execution +results report dispatch, disposition and applicable exit, signal, HTTP or +withholding details. Inspection and execution summaries show the shell or +HTTPS origin, and the project trust review displays the authored declaration. +`install --json` includes an optional `lifecycle` object with `pre`, `post`, +`diagnostics` and the package `disposition`. The report marks interruption +or pending recovery when applicable. Review notices go to stderr when a JSON +command writes or executes. + ## Adding and Inspecting Skills `source` is a local path, Git URL or shorthand accepted by core, well-known @@ -105,16 +208,17 @@ 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. -Requirement options on add map directly to declaration forms: +Requirement options on add populate a source's `requirement` mapping in +`agents.yaml`: | Option | Declaration | Matching versions | | --- | --- | --- | -| `--branch main` | `"branch": "main"` | Git branch | -| `--revision ` | `"revision": ""` | Git revision | -| `--exact 1.2.3` | `"exact": "1.2.3"` | Exact semantic version | -| `--from 1.2.3` | `"from": "1.2.3"` | At least 1.2.3, below 2.0.0 | -| `--up-to-next-minor-from 1.2.3` | `"upToNextMinor": "1.2.3"` | At least 1.2.3, below 1.3.0 | -| `--from 1.2.3 --to 1.8.0` | `"from": "1.2.3", "to": "1.8.0"` | Half-open range [1.2.3, 1.8.0) | +| `--branch main` | `requirement: {branch: main}` | Git branch | +| `--revision ` | `requirement: {revision: ""}` | Git revision | +| `--exact 1.2.3` | `requirement: {exact: "1.2.3"}` | Exact semantic version | +| `--from 1.2.3` | `requirement: {from: "1.2.3"}` | At least 1.2.3, below 2.0.0 | +| `--up-to-next-minor-from 1.2.3` | `requirement: {upToNextMinor: "1.2.3"}` | At least 1.2.3, below 1.3.0 | +| `--from 1.2.3 --to 1.8.0` | `requirement: {from: "1.2.3", to: "1.8.0"}` | Half-open range [1.2.3, 1.8.0) | Choose one requirement form; `--to` requires `--from`. With no requirement, core uses the latest version tag or the default branch if there are no tags. @@ -138,7 +242,7 @@ an `@` followed by one of these labels and `:`, so SSH locations such as `agents skills add larksuite/cli lark-base --from 1.0.0`. Use at most one requirement selector, one `@path:`, and one `@skill:`; percent-encode an `@` inside a value as `%40`. A selector and an option that give the same field must -agree; both replace the branch and path of a hosted tree URL. `agents.json` +agree; both replace the branch and path of a hosted tree URL. `agents.yaml` stores the structured fields, and the alias comes from the location. `instructions add` and `watch add` accept requirement and path selectors; `@skill:` applies to `skills add` and `skills list `. @@ -172,25 +276,40 @@ in it is deeper. `instructions init ` creates rejects an existing file. `instructions add [names…]` appends sections in argument order to the -scope's ordered list. With no names, one available section is added; several -available sections are listed for selection without writing declarations or -locks. `instructions list ` lists available sections with their -headings and descriptions; `instructions list` reports locked sections, +scope's ordered list. In a legacy single-list configuration, `--agent` sets +the list's recipients. With no names, one available section is added. When +several are available, `add` lists them for selection without writing declarations +or locks. `instructions list ` lists available sections with their +headings and descriptions. `instructions list` reports locked sections, physical targets and named prompts, including missing targets. Doctor reports their disk status. -Core generates each target in full: a notice line, then the sections as -written, in declared order. Project Codex, Claude Code, Cursor, and OpenCode +Core generates each legacy target in full with a notice line followed by the +sections in declared order. Project Codex, Claude Code, Cursor, and OpenCode share `AGENTS.md`; Gemini CLI uses `GEMINI.md`. User targets are the corresponding agent files under their configuration directories. A section with `paths` gets an `Applies when working on files matching …` line after its first heading; in project scope it goes to the target in the directory its patterns share, which must exist. When a project Claude file exists, core adds a managed import of `AGENTS.md` where needed. A local link must resolve to a -file in the project being written; user targets accept no local links. - -A file is generated when its first line is the notice; edits below the notice -are drift, which update and `install` replace. Any other file in a target +file in the project being written. User targets accept no local links. + +Antigravity and `agy` read one managed Markdown file per selected section. +Project rules live in `.agents/rules/` and user rules in `~/.gemini/config/rules/`. +Each file has `trigger: always_on` front matter. The rendered file, including +expanded references and front matter, can be at most 24,000 UTF-8 bytes. Core +reports the rule and size when that limit is exceeded. The preview also shows +the shared 20,000-token budget advisory for active global and always-on rules. +`agents instructions add team review --scope user --agent antigravity` +installs `review` as an Antigravity rule and preserves other sections' recipient +assignments. In `agents.yaml`, a section's `condition.agents` narrows the +instruction component's recipient list for that section. `agents install --scope user` +restores the locked selections. Core +migrates a Memex rule whose source path, revision, and bytes match. The preview +reports conflicts when a rule differs or unmanaged content occupies the destination. + +A legacy target is generated when its first line is the notice. Edits below the +notice are drift, which update and `install` replace. Any other file in a legacy target location, unless blank, stops `add`, `update --apply`, `remove` and `install`, even when the lock records it; move what it needs into instructions files, then `--replace` on `add` or `update --apply` shows its diff and takes it over. For @@ -208,24 +327,26 @@ section is placed from its `paths`, so one whose content is not available locally, an own file changed since the lock or a source section missing from the cache, is listed as unplaced; `agents install` fills the cache. -Declare named ChatGPT prompts in the scope's `agents.json`, using an existing +Declare named ChatGPT prompts in the scope's `agents.yaml`, using an existing source alias (here `rules`): -```json -{ - "instructions": { - "sections": ["rules:canonical-artifacts"], - "chatgpt": { - "weekly": { - "sections": ["rules:canonical-artifacts"], - "append": "prompt-custom.md" - } - } - } -} +```yaml +version: 1 +sources: + rules: + path: ../team-rules +components: + - kind: instructions + sections: + - {name: canonical-artifacts, source: rules} + chatgpt: + weekly: + sections: + - {name: canonical-artifacts, source: rules} + append: prompt-custom.md ``` -Merge this fragment with the declaration's existing sources and selections. +Add the named prompt to the instructions component's `chatgpt` mapping. `append` is optional and relative to the project root or HOME for user scope. Run `agents instructions update` to preview, then `--apply` to lock the prompt. `agents instructions render chatgpt weekly` writes the locked sections in @@ -239,6 +360,254 @@ removed prompts must be cleared in ChatGPT. Core detects changes to section bytes, membership, order, or append path. Edits to the append file's contents are read at render time and are not tracked as prompt changes. +## Manifest + +`manifest dump --json [--scope project|user]` reads the selected scope's existing +`agents.yaml` under a shared lock and prints core's encoded manifest JSON bytes. +`--json` is required. The project root is the current directory; change directory +to select another project. No `--path`, source argument or `--root` is accepted. + +Dump parses the local YAML document without resolving external groups, fetching +sources or secrets, inspecting native files, or starting configured programs. +Conditions and group references remain symbolic. It never creates state, replays +recovery or writes the declaration. A missing file, pending recovery, or invalid +manifest fails with exit 1 and empty stdout. YAML syntax, schema and domain +failures include path, line, UTF-8 byte column, severity and stable diagnostic +code on stderr; related locations follow when available. Invalid +arguments exit 64. See the [dump contract](ManifestDump.md) for encoding and +schema ownership. + +## Components + +Use `agents components inventory > inventory.cdx.json` to export the current project's +locked components as CycloneDX 1.6 JSON. Use `--format spdx` for SPDX 2.3. Set `SOURCE_DATE_EPOCH` to the build timestamp for reproducible output. Pass `--scope user` for user configuration. +Each source lists its locked version or revision and the components it provides. +Each component records its kind and target clients. The inventory reads committed +state and reports pending recovery before emitting a document. + +`components list` inspects the committed scope without resolving sources, +reading bindings or running recovery. `--json` includes exact logical identities, +inspection generations and occurrence IDs. A pending transaction fails rather +than recovering. A missing scope lists no components and creates no state. + +`components list --group ` discovers a canonical exported group +without installing it. A source can be an existing alias; a new path or repository +requires `--alias `. `--path` and the existing source requirement flags +select the source root and revision. Discovery resolves sources in Core’s +borrowed source session; it does not deploy components, resolve runtime bindings +or start programs. The returned graph includes existing scope intent as well as +the selected group. + +`components add` accepts the same source/group options and applies that canonical +group use. Source aliases must be distinct. `components remove ` removes a +managed component through Core’s exact selection API. Duplicate names require +`--kind`, `--identity` or an exact `--occurrence`; the command never chooses the first match. +`--occurrence` selects one listed authored occurrence; without it, the logical +component selection applies. `--agent` limits recipient removal. Core rejects +stale selections and protects unrelated domains and authored bytes. + +Top-level update, component add/remove and import support `--replace` for Core’s +explicit conflict takeover and `--changing-access` for its reported owner-only +permission changes. These options are passed to Core’s prepared request; Core +continues to decide ownership and safety. Install restores existing locked intent. + +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. + +## Import + +`import --format [--root ]` previews one explicit +producer document. The document is relative to root (cwd by default); Core +validates path containment and the profile. `--select` may be repeated for +profile-defined member selection. Profiles include `codexConfigV1`, +`claudeSettingsV1`, `cursorMCPV1`, `claudeCommandV1`, `geminiCommandV1`, +`openCodeCommandV2`, `rulesyncSourcesV1`, `apmManifest` and `apmLock`. +Core owns supported profile names and conversion rules. + +The default human report and `--json` describe source claims, converted component +kinds, resources, unresolved bindings and conversion diagnostics. This is an +import inspection, not an installed-state or deployment-success report. Preview +reads only the explicit producer inputs and does not write the scope or resolve +bindings. `--apply` captures the current scope, merges converted canonical intent +and uses the normal prepared transaction. Unresolved conversion diagnostics, +bindings, source alias conflicts or stale captured inputs prevent application. +Native producer deployment claims do not grant ownership of existing targets. +A separate apply invocation rereads the producer document. `--json --apply` is a +usage error. + +## Package Source Credentials + +`agents auth check --source ` uses the same selector as installation. +It reads the declaration and effective source policy for the selected scope, +which defaults to `project`. The report describes the provider, effective host +and port, transport, credential source category, and availability. An archive +route reports the mirror's host and uses the mirror's credential binding. +`agents auth check --host ` inspects host-wide bindings only, +with port 443 by default. `--scope` applies to selection by `--source`. +Core's trusted runtime configuration supplies provider registrations, mirrors, +and credential bindings. Project declarations select sources. + +Default inspection makes zero network requests and leaves credential resolution +to the operations that use it. SSH reports `ssh-managed` and delegated Git +authentication reports `delegated/unverified`. With `--source`, `--validate` +explicitly requests a check at the binding's authorized provider identity +endpoint, subject to current egress policy. Validation reports `accepted`, +`refused`, or `indeterminate`. Reports omit credentials, response bodies, and +subprocess diagnostics. A remote source with no available credential or an explicitly +refused credential produces its report and exits 1. An inconclusive provider check +with an available credential exits 0. With `--json`, the `validation` property is omitted when +validation was skipped. + +`agents auth export --source ` writes one explicitly exportable +credential to pipe-backed stdout, including shell command substitution. It uses +the same scoped selector and source policy. Core refuses ambiguous or opaque +bindings, terminals, and file redirection. Export has no JSON mode and stores +nothing. The pipe recipient is responsible for how it handles the value. + +## Download Cache + +Use `agents cache info` to see the cache location, store sizes and entry counts. +`agents cache clean` previews all disposable downloads. `agents cache prune +--days 30` previews Git revisions last used more than 30 days ago. Set +`--days 0` to review all earlier Git entries. Add `--apply` to remove eligible +entries or use its aliases `--force` and `--yes`. Each invocation checks the +current inventory. A changed or busy entry can survive cleanup. The result +lists skipped entries, failures and actual reclaimed bytes. Partial failure +returns a nonzero status and leaves completed removals in place. + +The user cache is shared across projects. Set `AGENTS_CACHE_DIR` to select its +root. Frozen deployment state and its required recovery contents stay with +the owning scope. + +## Bundles and Marketplaces + +Choose a local directory with `--directory `, a Git repository with +`--git `, or a hosted HTTPS index with `--index `. +Use `marketplace register ` with the address to save it. Search and +install accept the same address or a saved `--catalog `. Git sources +also accept `--ref` and `--subpath`. Use `marketplace stage --directory +` to add a bundle to a static hosting directory. The command prints the +index path. Deploy that directory with your hosting service. Project registrations take precedence over +user registrations of the same name. A relative registration is resolved +against its declaring scope. Installing records the catalog origin, so +changing a registration does not redirect an installed root. + +For a private hosted marketplace, register its index with `--scope user`. Bind a +token for the current command with `--token-env team=TEAM_MARKET_TOKEN`, where +`team` names that user registration. Resolving an index by another name still +uses its exact URL to select the credential. Repeat the option for dependencies +from other private indexes. For archive redirects to a trusted CDN, pass +`--download-origin https://cdn.example.com`. The CDN receives no market token. + +Run `agents bundle init` to scaffold a package. In that directory, select first-party instructions, complete skill directories, MCP servers or locked members in `author-package.json`. Run `agents bundle pack` to review the members, paths, findings and digest. Pass `--output` to write a portable archive. To publish the reviewed version, repeat the command with `--publish-to` and `--reviewed-digest`. A changed input requires a fresh review. Use `agents bundle plugin` to inspect a client-native distribution and `--output` to write it. For a Codex marketplace, supply both `--marketplace ` and `--category `. Plugin exports take the author and description from the project specification. + +Use `agents export-patch --dry-run --json` to review edits to deployed copies. +Each patch identifies its producer, base and affected paths and includes the exact +patch text. The review lists any skipped files with their reasons. Run +`agents export-patch -o ` to write the patches. The default output is +`patches/` in the current project. Identical files can be reused. A conflicting +file is preserved and the command reports a partial export with a failing status. + +Use `bundle export` with an identity from `components list --json` for each +member. Repeat `--dependency '[CATALOG:]PACKAGE@REQUIREMENT'` to declare the +package's edges. An unqualified edge uses the catalog that publishes the +bundle. A qualified edge records the registered Git repository or the canonical HTTPS index URL. +`bundle inspect` lists the dependencies and selectable entry IDs. Publish a +dependency-bearing archive to a catalog and install it through +`marketplace install`. `bundle import` applies an archive directly and +requires a self-contained bundle. + +`--package-version ` chooses an exact release. `--requirement` takes +an exact version, `major:1.2.0` (up to the next major), +`minor:1.2.0` (up to the next minor), or a half-open range such as +`'1.2.0..<2.0.0'`. Without a constraint, a new install selects the latest +release. A graph upgrade keeps the root's constraint and recipients unless +you explicitly replace them. Use `--requirement` to change the constraint or +`--package-version` to pin an exact release. Exact leaf installs made without +graph options retain their existing upgrade behavior and can advance to the +newest release by default. + +Use `agents marketplace lock` to resolve the package roots already in the declaration. Add `--apply` to save the frozen graph for later deployment. + +Use `--lock-only` with marketplace install, upgrade or remove to review the exact releases and target selections for a later deployment. Add `--apply` to save that pending lock. Existing deployed files stay in place. Run `agents marketplace deploy` to preview native changes from the frozen resources, then add `--apply` to deploy them. + +Use `marketplace resolve` for read-only discovery. With no arguments it +resolves the scope's declared graph roots. Supply a package and catalog to +discover a prospective root. The result lists dependencies, available +members, the locked version, the selected eligible version and the highest +published version. The latest release can be outside the graph's constraints. +`marketplace outdated ` uses upgrade preferences to show +eligible changes for an installed root. `marketplace deps` and +`marketplace why ` read committed state without opening catalogs. + +With `--agent`, installation selects all members of the root release by +default. Repeat `--component` to select its entry IDs or repeat `--member` to +select logical members of the root or its dependencies. A member has the +form `[CATALOG:]PACKAGE/KIND/NAME`, where kind is `skills`, `instructions` or +`mcpServer`. Unqualified members use the root's catalog. Every named agent +receives the selected members. On upgrade, an explicit member list replaces +the root's selections. A dependency can be resolved with no selected native +members. `--metadata-only` installs a root with an empty selection. On an +existing root this previews removal of that root's current selections. + +`marketplace install`, `upgrade` and `remove` preview by default. With +`--apply` they recheck the preview and commit the graph and its native +deployments together. Use `--binding NAME=ENV_VAR` for selected components that +need runtime values. On install, `--replace` offers to replace conflicting +instruction content in the preview. Removing one root keeps versions and +recipients still required by another root. Top-level `agents install` +restores the committed packages without rediscovering catalog releases. + +```sh +agents marketplace resolve onboarding --catalog team --requirement 'major:1.0.0' +agents marketplace install onboarding --catalog team --requirement 'major:1.0.0' \ + --agent codex --member onboarding/mcpServer/handbook --member shared/skills/review +agents marketplace why shared +agents marketplace upgrade onboarding --apply +``` + +## MCP Registry + +Use `mcp search` to browse the registry, then `mcp show` to inspect an exact version, +its numbered installation choices and input requirements. Set `MCP_REGISTRY_URL` to use a team +registry by default. The public registry is the default when the variable is unset. Pass +`--registry ` to override the endpoint for one command and `--token-env ` +when it requires bearer authentication. +The token is read for the registry request. Search and inspection leave the selected scope unchanged. + +Use `mcp add` to preview installation under the chosen name for one or more `--agent` recipients. +Pass the same `--server-version` and `--choice` that you inspected. A server with a single +choice selects it by default. Map requested inputs with `--input INPUT=ENV_VAR`. +Apply the configuration with `--apply`. Native private materialization uses the ordinary +`--binding` and `--changing-access` options when the preview identifies that need. + +## Runtime Bindings and MCP Tests + +`install`, top-level `update`, component add/remove, `import` and `mcp test` +accept repeated `--binding NAME=ENV_VAR`. The mapping names the only environment +variable that may supply that symbolic secret binding. At most 256 distinct +mappings are accepted; each mapping is at most 4096 UTF-8 bytes and each requested +value at most 1 MiB. Missing or invalid values identify only the symbolic binding. +No command is evaluated and no credential store or other client configuration is +read. Mapping validation does not read values. Only Core’s actual provider call +during apply or an explicit MCP test reads the named variable; previews, list, +doctor and help do not resolve it. Native `{env: NAME}` bindings remain Core’s +ordinary runtime environment references. + +`mcp test ` selects one managed MCP server using the same exact identity +and occurrence options as component removal. It captures Core’s selected typed +snapshot before testing, without refreshing sources or parsing native client +configuration. This explicit command can start its displayed stdio process or +contact its configured HTTP/SSE endpoint. It initializes the MCP protocol and +discovers tools; it does not apply configuration or change the scope ledger. +The JSON result contains transport, outcome, issue code, protocol version, +redacted tool metadata, elapsed time and cleanup status. Human output contains +outcome and redacted tool names. Successful discovery or a handshake with no tools +exits 0; incomplete/failed tests or incomplete cleanup exit 1. Core owns timeout, +redaction and owned process/resource cleanup. This result describes the explicit +test, independently of a native client’s authentication, trust and tool permissions. + ## Watch `watch add ` subscribes without installing content and records the @@ -314,7 +683,7 @@ baselines, installations, or source working trees. Uncommitted source files are ignored. Scheduling checks is left to the caller. Watch baselines live in `.agent/agents.watch` for project scope or -`~/.agents/agents.watch` for user scope. `agents.json` owns subscriptions. +`~/.agents/agents.watch` for user scope. `agents.yaml` owns subscriptions. A missing subscription suggests `run 'agents watch' to list subscriptions`; an invalid revision suggests providing a Git revision that resolves to a commit in the watched source. Operation failures exit 1; invalid options and unknown @@ -457,9 +826,9 @@ This reports unrecorded membership, not absent files. An existing live link can produce no physical diff, but applying still rejects an entry the scope does not manage. Preview does not grant ownership of existing files. -`agents update --apply` prepares skills and instructions under one writer lock, +`agents update --apply` prepares all components under one writer lock, prints the combined report once, and applies that exact preparation in one -transaction. Both kinds and their merged state commit together. It prints +transaction. All selected kinds and their merged state commit together. It prints completion lines only after the combined operation returns successfully. Recovery retries the entire preparation and displays its fresh report. `No changes.` uses core's combined `hasChanges`, which also covers state-only @@ -473,9 +842,9 @@ Updated recipients were installed before and remain installed; added recipients have new membership. Agent lists are comma-separated and sorted by agent ID. Pins use the same version and seven-character revision format as previews. When both pins are unavailable, the update line is `Updated for .` -Unchanged skills print no completion. Instruction target -completions print `Updated .` Changed ChatGPT prompts are named for -re-pasting after a combined apply. There is no generic success banner. +Unchanged skills print no completion. Instruction target completions describe +the file action as `Created .`, `Updated .`, or `Removed .` +Changed ChatGPT prompts are named for re-pasting after a combined apply. A preview can become stale; a separate `--apply` invocation prepares again and displays the content it will actually write. `--json --apply` is a usage error. @@ -486,7 +855,7 @@ Installed pdf for claude-code, codex (link). Added code-review, commits to AGENTS.md (claude-code, codex). Updated pdf for claude-code, codex: 6c09c94 -> 9661957. Updated AGENTS.md. -Removed commits from AGENTS.md. +Removed ~/.gemini/config/rules/example.md. Removed pdf for claude-code, codex. ``` @@ -496,11 +865,12 @@ and its diff. Instruction removal prints target diffs before its completion lines, and `Left in place because it differs from its generated version` for an edited target it keeps. -`install` restores skills, then instruction targets, using exact locked pins, +`install` restores all components in one transaction, using exact locked pins, hashes, modes, and recipients. It does not resolve newer versions and takes no -source argument. Unavailable pins, content that fails digest verification, and -own instructions files changed since the lock cause failure; run -`agents instructions update --apply` to record an edited own file. +source argument. Unavailable pins and content that fails digest verification cause +failure. Own instructions are restored from their locked content; edits to their +source files remain untouched and doctor reports them as changed. Run +`agents instructions update --apply` to adopt those edits into the lock and targets. `skills remove` requires names and removes their declarations, files, and lock entries. With `--agent`, it removes only those recipients. Removing a member of an `all` @@ -509,12 +879,12 @@ selection records an exclusion so an update does not reinstall it. `skills init [name]` creates a skill directory and `SKILL.md` in the current directory; without a name it creates `SKILL.md` directly there. Existing files are errors. -Top-level install runs one core operation per kind, in order. Each kind commits -its own transaction; an instruction install failure does not roll back a -completed skill install. Its recovery retry is scoped to the failing operation. +Top-level install uses Core’s single restore operation. Preparation failure leaves +all domains unchanged, and completion or successful JSON is emitted only after +the entire restore succeeds. Recovery retries the whole restore. A failed combined update exits 1 and prints no completion or successful JSON -report. Preparation errors leave both kinds unchanged. Apply errors report +report. Preparation errors leave all selected kinds unchanged. Apply errors report core's confirmed outcome: no update applied, committed with a later failure, or recovery required. A committed outcome calls for inspection with `agents doctor` in the same scope; recovery requires an applying operation in the same scope. @@ -522,14 +892,16 @@ Concurrent external edits can invalidate a preparation and remain untouched. ## Doctor and State -Doctor reports skills first, then instructions for each root. Skill checks +Doctor reports skills, instructions and other managed component deployments for each root. +Component checks use Core’s read-only inventory, report missing, drifted or +unverified deployments as errors, and retain pending recovery without replaying it. Skill checks include missing installations, drift, broken links, newer matching source revisions, and uncommitted source content. Instruction checks include missing or drifted targets, locked targets that agents did not generate, own files changed since the lock, links that no longer resolve, missing locks, sections at both scopes, Claude forwarding (including a Claude file that hides a nested `AGENTS.md`) and ancestor files, Codex override files and the project size limit, source changes, and -invalid configuration. `--root` audits both kinds. +invalid configuration. `--root` audits every managed kind. With `--ci`, a missing or changed locked skill or instruction target also produces exit status 1. An available upstream update alone remains informational. Use `--require-organization-policy` when CI must load an organization install policy or organization source allowlist. The audit checks locked sources against each applicable source policy. A violation or an unreadable policy produces an error and exit status 1. `--root` accepts multiple directories, either after one option or repeated. 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 @@ -537,16 +909,25 @@ current directory and user scope uses HOME. | Scope | Declaration | Lock | Cache | | --- | --- | --- | --- | -| Project | `.agent/agents.json` | `.agent/agents.resolved` | `.agent/cache/` | -| User | `~/.agents/agents.json` | `~/.agents/agents.resolved` | `~/.agents/cache/` | - -A project commits its declaration and lock; the cache stays local. Both files -are standard JSON in Prettier's default layout, with sorted keys and 80-column -arrays. Every command that writes state rewrites a file in another layout, -including the one earlier versions wrote, even when its content is unchanged. -To normalize a scope in one pass, run `agents instructions update --apply` -(with `--scope user` for `~/.agents`); it may report no instruction changes -while rewriting the files. +| Project | `.agent/agents.yaml` | `.agent/agents.resolved` | `.agent/cache/` | +| 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), +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 +commands use core's deployable subset; unsupported deployment constructs produce +located diagnostics, while dump accepts the complete format. Add, remove and +recipient edits preserve comments and bytes outside the supported edit. +If declaration semantics are unchanged, the original bytes stay untouched, +including authored formatting. An unchanged update also leaves lock bytes +untouched. `agents.resolved` remains tool-owned JSON, formatted by core when it +changes. + +An empty scope can be inspected without creating state. `manifest dump` requires +an existing declaration and reports its selected path when absent. Lock or watch +state without `agents.yaml` is an error; restore the declaration before retrying. Project roots are the current directory, not a search up the Git ancestry. Core resolves installation locations, including `CODEX_HOME`, @@ -566,6 +947,56 @@ recovery, run `agents install --scope user` for `~/.agents`, or run Commands that change a scope finish pending recovery before proceeding. When core reports recovery, the CLI prints a notice on stderr and retries that operation once. A second recovery or any other failure stops the command. +When core reports an unresolved transaction conflict, doctor emits error checks +`unresolved-transaction` (skills) and `unresolvedTransaction` (instructions), +retains core's owner-action message and locations, and exits 1. Inspect those +locations and resolve the conflict before retrying. Read operations preserve +both pending journals and conflicts. + +## Content Audit + +`agents audit` inspects recognized local prompt surfaces in the current +directory (project scope) or HOME (`--scope user`). It discovers prompts even +before a lock exists. Repeat `--agent` to limit discovery to selected clients: +`codex`, `claude-code`, `cursor`, `gemini-cli`, `opencode`, or `antigravity`. +Scope scans include scope-wide prompt surfaces and check present, admitted +managed content against recorded hashes where available. For deployment +presence, source policy, and full deployment drift, use `agents doctor`. + +`--file ` inspects one file inside the selected scope. Relative paths +resolve from the current directory. It accepts recognized native documents +and text prompts, including `.md`, `.mdc`, `.txt`, and `.prompt`. Native +documents contribute only recognized prompt fields. An explicit file scan +uses recorded ownership without comparing recorded content hashes. + +All scan formats go to stdout. Markdown is the default and summarizes +scanned, skipped, and incomplete targets. JSON includes `targets`, `findings`, +`passesCI`, and `ciExitCode`. SARIF 2.1.0 reports findings for code scanning. +Locations are scope-relative. Native findings identify the decoded prompt +field and include physical coordinates when Core can map them. Skipped +targets, such as a native document without prompt fields, are distinct from +incomplete coverage. Discovery stays inside the scope, skips protected paths +and nested repositories, and admits linked skills through matching ledger +entries. Incomplete coverage is a critical finding, including when an +admitted prompt is unreadable or scope recovery is pending. + +| Exit | Scan | Scan with `--ci` | +| --- | --- | --- | +| 0 | Clean or informational findings only | No critical findings | +| 1 | Critical findings, including incomplete coverage or detected recorded-content drift | Critical findings | +| 2 | Warning findings without critical findings | Unused | +| 64 | Invalid arguments | Invalid arguments | + +Use `agents audit --file AGENTS.md --strip` to preview deletions by location, +Unicode code point, and reason. The preview shows no prompt text and leaves +the file untouched. Rerun with `--apply` to prepare and apply a checked preview +in that invocation. Core verifies the file identity and bytes before +publishing the replacement. Strip accepts one regular, unshared, +non-executable UTF-8 text prompt and preserves all other bytes. It exits 0 +on a successful preview or apply, or 1 on refusal or failure. Use the scan +again to check the result. Native settings and linked files require manual +edits. If you edit a managed file in place, update its source and refresh +the deployment as needed. ## Output and Exit Status @@ -587,14 +1018,14 @@ including ESC, CR, C1, and bidi controls, use visible escapes: ```text Error: No ChatGPT prompt named 'daily' is declared. - Declare it under instructions.chatgpt in agents.json and run 'agents instructions update --apply'. + Declare it under chatgpt in the instructions component of agents.yaml and run 'agents instructions update --apply'. Error: Unknown option '--all'. Did you mean '--path'? Run 'agents --help' for usage. ``` Git failures name the operation and source, followed by Git's diagnostics and -a remedy. For a source alias `missing` declared in `.agent/agents.json` as -`{"git": "file://localhost/missing/skills.git"}`, a failed add reports: +a remedy. For a source alias `missing` declared in `.agent/agents.yaml` as +`sources: {missing: {url: "file://localhost/missing/skills.git"}}`, a failed add reports: ```text $ agents skills add missing demo @@ -624,8 +1055,10 @@ Unknown commands and subcommands report `Unknown command ''` and exit Command-path validation stops at `--`; leaf command positionals remain arguments. Doctor's `ok` means there are no error checks; warnings do not make it false. -Instruction `invalidTarget`, `foreignTarget`, `invalidLink`, `invalidConfiguration`, and -`stateUnavailable` diagnostics and both pending-recovery findings are errors. +Instruction `invalidTarget`, `foreignTarget`, `invalidLink`, +`invalidConfiguration`, `stateUnavailable` and `unresolvedTransaction` diagnostics, +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 @@ -633,8 +1066,12 @@ one object and a trailing newline; recovery notices remain on stderr. ## JSON Schemas -Every report has an integer `schemaVersion`: 2 for the update, instruction -update and install reports, 1 for the others. Object keys are sorted. Arrays +The [manifest dump contract](ManifestDump.md) is produced by core and printed +byte-for-byte, with no CLI wrapper or scope field. The remaining schemas are +CLI-owned reports, independent of core's state encodings. + +Every report has an integer `schemaVersion`: 2 for the manifest dump, update, +instruction update and install reports, 1 for the others. Object keys are sorted. Arrays follow core's deterministic ordering; instruction section lists preserve selection order, targets and prompt names are sorted, and doctor roots retain input order. @@ -653,17 +1090,32 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | Command | Schema | Required root fields | | --- | --- | --- | +| `manifest dump --json` | [Manifest dump contract](ManifestDump.md) | Producer-owned manifest object | | `skills list --json` | [Installed list](Schemas/installed-list.schema.json) | `schemaVersion`, `kind: "installed"`, `scope`, `skills` | | `skills list --json` | [Source list](Schemas/source-list.schema.json) | `schemaVersion`, `kind: "source"`, `scope`, `source`, `skills` | -| `update --json`, `skills update --json` | [Update](Schemas/update.schema.json) | `schemaVersion`, `scope`, `changed`, `skills`; top-level update also emits `instructions` | +| `update --json`, `skills update --json` | [Update](Schemas/update.schema.json) | `schemaVersion`, `scope`, `changed`, `skills`; top-level update also emits `instructions` and `components` | | `instructions list --json` | [Managed instructions](Schemas/instructions-installed-list.schema.json) | `schemaVersion`, `kind: "installed"`, `scope`, `sections`, `targets`, `prompts` | | `instructions list --json` | [Instruction source](Schemas/instructions-source-list.schema.json) | `schemaVersion`, `kind: "source"`, `scope`, `source`, `sections` | | `instructions update --json` | [Instruction update](Schemas/instructions-update.schema.json) | `schemaVersion`, `scope`, `changed`, `instructions` | | `instructions export --json` | [Instruction export](Schemas/instructions-export.schema.json) | `schemaVersion`, `scopes` | | `watch status --json`, `watch --json` | [Watch status](Schemas/watch-status.schema.json) | `schemaVersion`, `scope`, `sources` | | `watch diff --json` | [Watch diff](Schemas/watch-diff.schema.json) | `schemaVersion`, `scope`, `source` | -| `install --json` | [Install](Schemas/install.schema.json) | `schemaVersion`, `scope`, `skills`, `instructions` | +| `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` | +| `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` | +| `mcp show --json` | [MCP registry server](Schemas/mcp-registry-server.schema.json) | `schemaVersion`, `name`, `version`, `description`, `choices` | +| `mcp add --json` | [Update](Schemas/update.schema.json) | `schemaVersion`, `scope`, `changed`, `skills`, `instructions`, `components` | +| `auth check --json` | [Source credential status](Schemas/auth-check.schema.json) | `schemaVersion`, `transport`, `availability`, and optional `scope`, `provider`, `effectiveHost`, `credentialSource`, `validation` | +| `cache info/clean/prune --json` | [Download cache](Schemas/cache.schema.json) | See the inventory, preview and removal alternatives. | +| `marketplace resolve --json` | [Marketplace resolution](Schemas/marketplace-resolution.schema.json) | `schemaVersion`, `scope`, `roots`, `nodes` | +| `marketplace install/upgrade/remove --lock-only --json` | [Pending lock](Schemas/marketplace-pending.schema.json) | `schemaVersion`, `resolution`, `pendingDigest`, `changed`, `policyFindings` | +| `marketplace deploy --json` | [Update](Schemas/update.schema.json) | Native changes from the pending lock | +| `marketplace install/upgrade/remove --json` for graph packages | [Marketplace preview](Schemas/marketplace-preview.schema.json) | `schemaVersion`, `resolution`, `update`, `affectedRoots`, `pinChanges` | +| `marketplace install/upgrade/remove --json` for exact leaf packages | [Update](Schemas/update.schema.json) | `schemaVersion`, `scope`, `changed`, `skills`, `marketplaceChanges` when pins change | +| `mcp test --json` | [MCP test](Schemas/mcp-test.schema.json) | `schemaVersion`, `kind`, `transport`, `outcome`, `cleanupComplete`, `elapsed`, `tools` | An empty installed list: @@ -693,7 +1145,7 @@ 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"`; existing fields and IDs +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. @@ -705,10 +1157,13 @@ The shared [instruction definitions](Schemas/instructions.schema.json) describe: `beforeAgents` (previous agent IDs, or `null` when no lock entry existed), `afterAgents` (planned agent IDs, empty when no longer managed), optional `before`/`after` file snapshots, optional `drift` (`clean`, `drifted` or - `missing`, against the previous lock), and `foreign` (applying writes over a - file that agents did not generate). Agent IDs use their raw values in + `missing`, against the previous lock), and `foreign` (the proposed destination + holds a file that agents did not generate). Agent IDs use their raw values in deterministic order. - `changedPrompts`: prompt names whose content definition changed. +- `advisories`: optional nonblocking messages from Core, such as the shared + Antigravity rule budget, which can appear on a preview without changes. +- `conflicts`: optional messages from Core about conditions that block apply. - `lockMissing`: no scope lock existed when the operation began. - `changed`: applying changes the declaration, locked state, or target bytes, including recipient-only changes with identical file bytes and targets that @@ -718,6 +1173,11 @@ Instruction file snapshots use the same `{ "kind": "file", "base64": "…" }` shape as skill files. `install --json` reports restored skill rows and instruction restoration differences; instruction `sections` and `changedPrompts` are empty because install never resolves new content. +Top-level update and install add `components` without changing their version 2 +contracts. Component rows identify kind, name, source, destination, recipients, +format, ownership, symbolic before/after values, required binding names, resource +hashes, effective readers and planned permission changes. Provider values are +never included. Scoped skill/instruction reports retain their existing shapes. The definitions are CLI-owned and do not expose core's encoded lock objects. Instruction source listings add each file's `level`, `description` and `paths` @@ -738,3 +1198,24 @@ Each baseline is either `{ "revision": "" }` or `kind: "file"`, `base64`, and boolean `executable`. Directory and symlink entries use the same shapes as update previews. Status omits file snapshots. Artifact digests may change with zero file differences; `fileCount` remains zero. + + +## Source policies + +Run `agents policy status --scope project` to inspect the organization policies selected for a workspace. Select an organization install policy by setting `AGENTS_USER_ORGANIZATION_POLICY` or `AGENTS_PROJECT_ORGANIZATION_POLICY` to an absolute file path, an HTTPS policy URL, or `github:OWNER/REPO`. The report shows each governing document and its digest. Add `--json` for the full findings with subject, rule, authority and dependency path. Blocking findings cause exit status 1. Advisory findings remain visible in both this report and `agents doctor --ci`. + +Use `agents policy show --scope project` to see the applicable organization, +user and project policies. Add `--json` for structured output. Preview a file +with `agents policy set rules.yaml --scope project` and add `--apply` to save +it in `.agent/source-policy.yaml`. Use `--scope user` to edit +`~/.agents/source-policy.yaml`. Set `AGENTS_ORGANIZATION_SOURCE_POLICY` to the +path of an administrator-managed policy. A source must pass every applicable +layer. Run `agents doctor --ci` to check installed configuration in CI. + +```yaml +version: 1 +allow: + - git: https://github.com/example/team-skills + - http: https://registry.example.org + - inline +``` diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md new file mode 100644 index 0000000..e611b70 --- /dev/null +++ b/Documentation/Reference/ManifestDump.md @@ -0,0 +1,33 @@ +# Manifest Dump Contract + +`agents manifest dump --json [--scope project|user]` exposes the manifest +format's JSON contract. The authoritative schema and byte contract +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/0.3.1/Documentation/Reference/Manifest.md#bounds-and-dump), +including its semantic records and evolution rules. The CLI prints +`ManifestDump.encodedJSON()` bytes unchanged; it does not define another +semantic representation or wrap the result in a CLI report. + +The current object identifies `schemaVersion: 2`, `kind: "manifest"`, +`format: "yaml"` and `manifestVersion: 1`. It contains `sourceDigest`, +`declaration`, `locations` and `diagnostics`. These fields, their normalized +values, discriminants, ordering and defaults are owned by the linked manifest +contract. Locations +use the stable document identity `manifest`, with half-open UTF-8 byte offsets +and 1-based line/UTF-8-byte-column coordinates in the original YAML bytes. The +source digest covers original bytes, so comments can change digest and locations while declaration values stay equal. + +Output is one UTF-8 object with sorted keys, two-space indentation and a trailing +LF. It includes symbolic conditions and group references; secrets and runtime +environment references remain symbolic. Readers ignore unknown object keys and +reject unsupported schema versions or unknown semantic discriminants. + +The selected path and scope determine the input and are not extra JSON fields. +A failure emits no partial JSON. The CLI owns argument validation, error +presentation and exit codes, documented in [CLI Reference](CLI.md#manifest). +`NativeValue` records retain their numeric identity: integers have kind +`integer`, while decimals have kind `decimal` and a string `value` preserving +exact decimal text. Semantic location pointers remain indexed, including +`/components//chatGPT/` for YAML `chatgpt` entries. + +Other [CLI JSON schemas](CLI.md#json-schemas) describe independent report shapes; +they do not describe declaration storage or this manifest object. diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index 6258017..dfe0671 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -39,8 +39,11 @@ changelog entry in the requirement's final delivery candidate. ## Verify the Release Commit -The CLI requires macOS 15 or later and Swift 6.3 or later to build. Shared CI -compiles and tests only with Xcode 26.6 on `macos-26`. +The CLI builds from source on macOS and Linux; [Package.swift](../../Package.swift) +defines the minimum toolchain and macOS versions. Shared CI validates Xcode +26.6 on `macos-26` and the pinned Swift 6.4.1 Noble Linux image in +[package configuration](../../.github/swift-package.json). The local validation +commands below use macOS's Xcode tools. Use a clean task or detached worktree at the exact merged release candidate. Do not build in the main checkout. Fetch tags, record `release_commit`, and diff --git a/Documentation/Reference/Schemas/auth-check.schema.json b/Documentation/Reference/Schemas/auth-check.schema.json new file mode 100644 index 0000000..d3f9a1a --- /dev/null +++ b/Documentation/Reference/Schemas/auth-check.schema.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Package source credential status", + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "scope": { "enum": ["project", "user"] }, + "provider": { "enum": ["github", "gitlab"] }, + "effectiveHost": { "type": "string" }, + "transport": { "enum": ["local", "git", "http", "https", "ssh", "archive"] }, + "credentialSource": { "enum": ["supplied", "environment", "opaque"] }, + "availability": { + "enum": ["available", "unavailable", "unconfigured", "delegated/unverified", "ssh-managed"] + }, + "validation": { "enum": ["accepted", "refused", "indeterminate"] } + }, + "required": ["schemaVersion", "transport", "availability"], + "additionalProperties": false +} diff --git a/Documentation/Reference/Schemas/cache.schema.json b/Documentation/Reference/Schemas/cache.schema.json new file mode 100644 index 0000000..44e94ca --- /dev/null +++ b/Documentation/Reference/Schemas/cache.schema.json @@ -0,0 +1,246 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Download cache operations", + "oneOf": [ + { + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "root": { + "type": "string" + }, + "totalBytes": { + "type": "integer", + "minimum": 0 + }, + "stores": { + "type": "array", + "items": { + "$ref": "#/$defs/usage" + } + }, + "entries": { + "type": "array", + "items": { + "$ref": "#/$defs/entry" + } + }, + "issues": { + "type": "array", + "items": { + "$ref": "#/$defs/issue" + } + } + }, + "required": [ + "schemaVersion", + "root", + "totalBytes", + "stores", + "entries", + "issues" + ] + }, + { + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "root": { + "type": "string" + }, + "operation": { + "enum": [ + "clean", + "prune" + ] + }, + "days": { + "type": "integer", + "minimum": 0 + }, + "totalBytes": { + "type": "integer", + "minimum": 0 + }, + "candidates": { + "type": "array", + "items": { + "$ref": "#/$defs/entry" + } + }, + "issues": { + "type": "array", + "items": { + "$ref": "#/$defs/issue" + } + } + }, + "required": [ + "schemaVersion", + "root", + "operation", + "totalBytes", + "candidates", + "issues" + ], + "if": { + "properties": { + "operation": { + "const": "prune" + } + } + }, + "then": { + "required": [ + "days" + ] + } + }, + { + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "root": { + "type": "string" + }, + "operation": { + "enum": [ + "clean", + "prune" + ] + }, + "days": { + "type": "integer", + "minimum": 0 + }, + "reclaimedBytes": { + "type": "integer", + "minimum": 0 + }, + "removed": { + "type": "array", + "items": { + "$ref": "#/$defs/entry" + } + }, + "skipped": { + "type": "array", + "items": { + "$ref": "#/$defs/entry" + } + }, + "failures": { + "type": "array", + "items": { + "$ref": "#/$defs/issue" + } + } + }, + "required": [ + "schemaVersion", + "root", + "operation", + "reclaimedBytes", + "removed", + "skipped", + "failures" + ], + "if": { + "properties": { + "operation": { + "const": "prune" + } + } + }, + "then": { + "required": [ + "days" + ] + } + } + ], + "$defs": { + "store": { + "enum": [ + "git", + "http", + "deployed" + ] + }, + "entry": { + "type": "object", + "properties": { + "store": { + "$ref": "#/$defs/store" + }, + "id": { + "type": "string" + }, + "object": { + "type": "string" + }, + "bytes": { + "type": "integer", + "minimum": 0 + }, + "lastUsed": { + "type": "string", + "format": "date-time" + }, + "pendingDisposal": { + "type": "boolean" + } + }, + "required": [ + "store", + "id", + "object", + "bytes", + "lastUsed", + "pendingDisposal" + ] + }, + "issue": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "path", + "reason" + ] + }, + "usage": { + "type": "object", + "properties": { + "name": { + "$ref": "#/$defs/store" + }, + "entries": { + "type": "integer", + "minimum": 0 + }, + "bytes": { + "type": "integer", + "minimum": 0 + } + }, + "required": [ + "name", + "entries", + "bytes" + ] + } + } +} diff --git a/Documentation/Reference/Schemas/components-list.schema.json b/Documentation/Reference/Schemas/components-list.schema.json new file mode 100644 index 0000000..c7280ff --- /dev/null +++ b/Documentation/Reference/Schemas/components-list.schema.json @@ -0,0 +1,94 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Component inspection, version 1", + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "kind": { + "const": "components" + }, + "scope": { + "enum": [ + "project", + "user" + ] + }, + "components": { + "type": "array", + "items": { + "type": "object", + "properties": { + "identity": { + "type": "string" + }, + "generation": { + "type": "string" + }, + "kind": { + "type": "string" + }, + "name": { + "type": "string" + }, + "source": { + "type": "string" + }, + "group": { + "type": "string" + }, + "revision": { + "type": "string" + }, + "agents": { + "type": "array", + "items": { + "type": "string" + } + }, + "occurrences": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "source": { + "type": "string" + }, + "manifestPath": { + "type": "string" + }, + "consumerEditable": { + "type": "boolean" + } + }, + "required": [ + "source", + "manifestPath", + "consumerEditable" + ] + } + } + }, + "required": [ + "identity", + "generation", + "kind", + "name", + "source", + "agents", + "occurrences" + ] + } + } + }, + "required": [ + "schemaVersion", + "kind", + "scope", + "components" + ] +} diff --git a/Documentation/Reference/Schemas/components.schema.json b/Documentation/Reference/Schemas/components.schema.json new file mode 100644 index 0000000..d55079e --- /dev/null +++ b/Documentation/Reference/Schemas/components.schema.json @@ -0,0 +1,135 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Component update definitions", + "$defs": { + "change": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "name": { + "type": "string" + }, + "source": { + "type": "string" + }, + "revision": { + "type": "string" + }, + "version": { + "type": "string" + }, + "path": { + "type": "string" + }, + "format": { + "type": "string" + }, + "ownership": { + "type": "string" + }, + "agents": { + "type": "array", + "items": { + "type": "string" + } + }, + "changed": { + "type": "boolean" + }, + "requiredBindings": { + "type": "array", + "items": { + "type": "string" + } + }, + "effectiveReaders": { + "type": "array", + "items": { + "type": "string" + } + }, + "privateMaterialization": { + "type": "boolean" + }, + "before": { + "type": "string" + }, + "after": { + "type": "string" + }, + "resources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "hash": { + "type": "string" + }, + "executableFiles": { + "type": "object", + "additionalProperties": { + "type": "boolean" + } + } + }, + "required": [ + "path", + "hash", + "executableFiles" + ] + } + }, + "permissionChange": { + "type": "object", + "properties": { + "beforeOwner": { + "type": "integer" + }, + "beforeGroup": { + "type": "integer" + }, + "beforeMode": { + "type": "integer" + }, + "afterOwner": { + "type": "integer" + }, + "afterMode": { + "type": "integer" + }, + "ownerOnly": { + "type": "boolean" + } + }, + "required": [ + "beforeOwner", + "beforeGroup", + "beforeMode", + "afterOwner", + "afterMode", + "ownerOnly" + ] + } + }, + "required": [ + "kind", + "name", + "source", + "path", + "format", + "ownership", + "agents", + "changed", + "requiredBindings", + "effectiveReaders", + "privateMaterialization", + "resources" + ] + } + } +} diff --git a/Documentation/Reference/Schemas/doctor.schema.json b/Documentation/Reference/Schemas/doctor.schema.json index e184bf0..a415633 100644 --- a/Documentation/Reference/Schemas/doctor.schema.json +++ b/Documentation/Reference/Schemas/doctor.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Skill and instruction diagnosis, version 1", + "title": "Managed component diagnosis, version 1", "type": "object", "properties": { "schemaVersion": { @@ -32,7 +32,8 @@ "type": "object", "properties": { "id": { - "type": "string" + "type": "string", + "description": "Core diagnostic ID. Pending recovery and unresolved transaction IDs are reported as errors; unresolved transaction messages retain owner-action details." }, "status": { "enum": [ @@ -50,7 +51,11 @@ "kind": { "enum": [ "skills", - "instructions" + "instructions", + "components", + "sourcePolicy", + "organizationPolicy", + "marketplace" ] } }, diff --git a/Documentation/Reference/Schemas/import.schema.json b/Documentation/Reference/Schemas/import.schema.json new file mode 100644 index 0000000..e07ca2e --- /dev/null +++ b/Documentation/Reference/Schemas/import.schema.json @@ -0,0 +1,166 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Producer import inspection, version 1", + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "kind": { + "const": "import" + }, + "format": { + "type": "string" + }, + "producerRevision": { + "type": "string" + }, + "specificationStatus": { + "type": "string" + }, + "sources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "alias": { + "type": "string" + }, + "document": { + "type": "string" + }, + "pointer": { + "type": "string" + }, + "commit": { + "type": "string" + }, + "version": { + "type": "string" + }, + "developmentOnly": { + "type": "boolean" + } + }, + "required": [ + "alias", + "document", + "pointer", + "developmentOnly" + ] + } + }, + "components": { + "type": "array", + "items": { + "type": "object", + "properties": { + "document": { + "type": "string" + }, + "pointer": { + "type": "string" + }, + "kind": { + "type": "string" + } + }, + "required": [ + "document", + "pointer", + "kind" + ] + } + }, + "diagnostics": { + "type": "array", + "items": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "document": { + "type": "string" + }, + "pointer": { + "type": "string" + }, + "message": { + "type": "string" + } + }, + "required": [ + "code", + "document", + "pointer", + "message" + ] + } + }, + "bindings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "document": { + "type": "string" + }, + "pointer": { + "type": "string" + }, + "reason": { + "type": "string" + }, + "environmentVariable": { + "type": "string" + } + }, + "required": [ + "document", + "pointer", + "reason" + ] + } + }, + "resources": { + "type": "array", + "items": { + "type": "object", + "properties": { + "source": { + "type": "string" + }, + "path": { + "type": "string" + }, + "hash": { + "type": "string" + }, + "selected": { + "type": "boolean" + }, + "requiresStandaloneSource": { + "type": "boolean" + } + }, + "required": [ + "source", + "selected", + "requiresStandaloneSource" + ] + } + } + }, + "required": [ + "schemaVersion", + "kind", + "format", + "specificationStatus", + "sources", + "components", + "diagnostics", + "bindings", + "resources" + ] +} diff --git a/Documentation/Reference/Schemas/install.schema.json b/Documentation/Reference/Schemas/install.schema.json index a5c5775..c26dc14 100644 --- a/Documentation/Reference/Schemas/install.schema.json +++ b/Documentation/Reference/Schemas/install.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Skill and instruction restoration, version 2", + "title": "Component restoration, version 2", "type": "object", "properties": { "schemaVersion": { @@ -40,6 +40,15 @@ }, "instructions": { "$ref": "instructions.schema.json#/$defs/changes" + }, + "lifecycle": { + "$ref": "lifecycle.schema.json#/$defs/package" + }, + "components": { + "type": "array", + "items": { + "$ref": "components.schema.json#/$defs/change" + } } }, "required": [ diff --git a/Documentation/Reference/Schemas/instructions.schema.json b/Documentation/Reference/Schemas/instructions.schema.json index c629845..f746358 100644 --- a/Documentation/Reference/Schemas/instructions.schema.json +++ b/Documentation/Reference/Schemas/instructions.schema.json @@ -146,6 +146,18 @@ "items": { "type": "string" } + }, + "advisories": { + "type": "array", + "items": { + "type": "string" + } + }, + "conflicts": { + "type": "array", + "items": { + "type": "string" + } } }, "required": [ diff --git a/Documentation/Reference/Schemas/lifecycle.schema.json b/Documentation/Reference/Schemas/lifecycle.schema.json new file mode 100644 index 0000000..43f292b --- /dev/null +++ b/Documentation/Reference/Schemas/lifecycle.schema.json @@ -0,0 +1,237 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Lifecycle command reports, version 1", + "oneOf": [ + { + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "kind": { "const": "lifecycle-list" }, + "scope": { "$ref": "#/$defs/scope" }, + "ok": { "type": "boolean" }, + "diagnostics": { + "type": "array", + "items": { "$ref": "#/$defs/diagnostic" } + }, + "project": { "type": "string" }, + "projectTrusted": { "type": "boolean" }, + "allStartsWithheld": { "type": "string" }, + "actions": { + "type": "array", + "items": { "$ref": "#/$defs/action" } + } + }, + "required": ["schemaVersion", "kind", "scope", "ok", "diagnostics", "actions"] + }, + { + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "kind": { "const": "lifecycle-validation" }, + "scope": { "$ref": "#/$defs/scope" }, + "ok": { "type": "boolean" }, + "diagnostics": { + "type": "array", + "items": { "$ref": "#/$defs/diagnostic" } + } + }, + "required": ["schemaVersion", "kind", "scope", "ok", "diagnostics"] + }, + { + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "kind": { "const": "lifecycle-test" }, + "scope": { "$ref": "#/$defs/scope" }, + "ok": { "type": "boolean" }, + "diagnostics": { + "type": "array", + "items": { "$ref": "#/$defs/diagnostic" } + }, + "project": { "type": "string" }, + "projectTrusted": { "type": "boolean" }, + "allStartsWithheld": { "type": "string" }, + "actions": { + "type": "array", + "items": { "$ref": "#/$defs/action" } + }, + "event": { "$ref": "#/$defs/event" }, + "results": { + "type": "array", + "items": { "$ref": "#/$defs/result" } + }, + "interrupted": { "const": true } + }, + "required": ["schemaVersion", "kind", "scope", "ok", "diagnostics", "event", "actions"] + }, + { + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "kind": { "const": "lifecycle-init" }, + "scope": { "$ref": "#/$defs/scope" }, + "path": { "type": "string" }, + "digest": { "type": "string" }, + "originalDigest": { "type": "string" }, + "declaration": { "type": "object" }, + "saved": { "type": "boolean" } + }, + "required": ["schemaVersion", "kind", "scope", "path", "digest", "originalDigest", "saved"] + }, + { + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "kind": { "const": "lifecycle-trust" }, + "path": { "type": "string" }, + "rootID": { "type": "string" }, + "digest": { "type": "string" }, + "revision": { "type": "integer" }, + "notice": { "type": "string" }, + "declaration": { "type": "object" }, + "applied": { "type": "boolean" } + }, + "required": ["schemaVersion", "kind", "path", "rootID", "digest", "revision", "notice", "declaration", "applied"] + }, + { + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "kind": { "const": "lifecycle-trusted" }, + "roots": { + "type": "array", + "items": { "$ref": "#/$defs/root" } + } + }, + "required": ["schemaVersion", "kind", "roots"] + }, + { + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "kind": { "const": "lifecycle-untrust" }, + "roots": { + "type": "array", + "items": { "$ref": "#/$defs/root" } + } + }, + "required": ["schemaVersion", "kind", "roots"] + } + ], + "$defs": { + "action": { + "type": "object", + "properties": { + "authority": { "$ref": "#/$defs/authority" }, + "path": { "type": "string" }, + "event": { "$ref": "#/$defs/event" }, + "index": { "type": "integer" }, + "kind": { + "enum": [ + "command", + "http" + ] + }, + "target": { "type": "string" }, + "timeoutSeconds": { "type": "integer" }, + "withholding": { "type": "string" } + }, + "required": ["authority", "path", "event", "index", "kind", "target", "timeoutSeconds"] + }, + "diagnostic": { + "type": "object", + "properties": { + "authority": { "$ref": "#/$defs/authority" }, + "path": { "type": "string" }, + "event": { "type": "string" }, + "index": { "type": "integer" }, + "field": { "type": "string" }, + "message": { "type": "string" } + }, + "required": ["authority", "path", "message"] + }, + "result": { + "type": "object", + "properties": { + "action": { "$ref": "#/$defs/action" }, + "status": { "type": "string" }, + "dispatched": { "type": "boolean" }, + "withholding": { "type": "string" }, + "exitStatus": { "type": "integer" }, + "signal": { "type": "integer" }, + "httpStatus": { "type": "integer" }, + "stdoutBytes": { "type": "integer" }, + "stderrBytes": { "type": "integer" }, + "processGroupCleanedUp": { "type": "boolean" }, + "diagnostics": { + "type": "array", + "items": { "$ref": "#/$defs/diagnostic" } + } + }, + "required": ["action", "status", "dispatched", "stdoutBytes", "stderrBytes", "diagnostics"] + }, + "package": { + "type": "object", + "properties": { + "disposition": { + "enum": [ + "unchanged", + "committed", + "rolledBack", + "recoveryRequired" + ] + }, + "pre": { + "type": "array", + "items": { "$ref": "#/$defs/result" } + }, + "post": { + "type": "array", + "items": { "$ref": "#/$defs/result" } + }, + "diagnostics": { + "type": "array", + "items": { "$ref": "#/$defs/diagnostic" } + }, + "interrupted": { "const": true }, + "recoveryPending": { "const": true } + }, + "required": ["disposition", "pre", "post", "diagnostics"] + }, + "root": { + "type": "object", + "properties": { + "path": { "type": "string" }, + "rootID": { "type": "string" }, + "revision": { "type": "integer" }, + "digest": { "type": "string" }, + "pathExists": { "type": "boolean" } + }, + "required": ["path", "rootID", "revision", "pathExists"] + }, + "authority": { + "enum": [ + "administrator", + "user", + "project" + ] + }, + "event": { + "enum": [ + "pre-install", + "post-install", + "pre-update", + "post-update", + "pre-uninstall", + "post-uninstall", + "pre-compile" + ] + }, + "scope": { + "enum": [ + "project", + "user" + ] + } + } +} diff --git a/Documentation/Reference/Schemas/marketplace-pending.schema.json b/Documentation/Reference/Schemas/marketplace-pending.schema.json new file mode 100644 index 0000000..b8d8a56 --- /dev/null +++ b/Documentation/Reference/Schemas/marketplace-pending.schema.json @@ -0,0 +1,33 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Pending marketplace lock preview, version 1", + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "resolution": { + "$ref": "marketplace-resolution.schema.json" + }, + "pendingDigest": { + "type": "string", + "pattern": "^sha256:[0-9a-f]{64}$" + }, + "changed": { + "type": "boolean" + }, + "policyFindings": { + "type": "array", + "items": { + "$ref": "doctor.schema.json#/properties/roots/items/properties/checks/items" + } + } + }, + "required": [ + "schemaVersion", + "resolution", + "pendingDigest", + "changed", + "policyFindings" + ] +} diff --git a/Documentation/Reference/Schemas/marketplace-preview.schema.json b/Documentation/Reference/Schemas/marketplace-preview.schema.json new file mode 100644 index 0000000..a0dd1ea --- /dev/null +++ b/Documentation/Reference/Schemas/marketplace-preview.schema.json @@ -0,0 +1,25 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Marketplace graph update preview, version 1", + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "resolution": { "$ref": "marketplace-resolution.schema.json" }, + "update": { "$ref": "update.schema.json" }, + "affectedRoots": { "type": "array", "items": { "type": "string" } }, + "pinChanges": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { "$ref": "marketplace-resolution.schema.json#/$defs/nodeID" }, + "before": { "type": "string" }, + "after": { "type": "string" } + }, + "required": ["id"] + } + }, + "ownershipConflict": { "type": "string" } + }, + "required": ["schemaVersion", "resolution", "update", "affectedRoots", "pinChanges"] +} diff --git a/Documentation/Reference/Schemas/marketplace-resolution.schema.json b/Documentation/Reference/Schemas/marketplace-resolution.schema.json new file mode 100644 index 0000000..b424789 --- /dev/null +++ b/Documentation/Reference/Schemas/marketplace-resolution.schema.json @@ -0,0 +1,89 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Marketplace resolution, version 1", + "type": "object", + "properties": { + "schemaVersion": { "const": 1 }, + "scope": { "enum": ["project", "user"] }, + "roots": { "type": "array", "items": { "$ref": "#/$defs/root" } }, + "nodes": { "type": "array", "items": { "$ref": "#/$defs/node" } } + }, + "required": ["schemaVersion", "scope", "roots", "nodes"], + "$defs": { + "nodeID": { + "type": "object", + "properties": { + "package": { "type": "string" }, + "catalogKind": { "enum": ["directory", "git", "hosted"] }, + "catalogOrigin": { "type": "string" }, + "hostedIndex": { "type": "string", "format": "uri", "pattern": "^https://" }, + "subpath": { "type": "string" } + }, + "required": ["package", "catalogKind", "catalogOrigin"], + "if": { "properties": { "catalogKind": { "const": "hosted" } } }, + "then": { "required": ["hostedIndex"] } + }, + "catalog": { + "type": "object", + "properties": { + "kind": { "enum": ["directory", "git", "hosted"] }, + "location": { "type": "string" }, + "ref": { "type": "string" }, + "subpath": { "type": "string" } + }, + "required": ["kind", "location"] + }, + "root": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "node": { "$ref": "#/$defs/nodeID" }, + "requirement": { "type": "string" }, + "selections": { "type": "array", "items": { "$ref": "#/$defs/selection" } } + }, + "required": ["name", "node", "requirement", "selections"] + }, + "selection": { + "type": "object", + "properties": { + "package": { "type": "string" }, + "catalog": { "$ref": "#/$defs/catalog" }, + "kind": { "$ref": "#/$defs/memberKind" }, + "name": { "type": "string" }, + "targets": { "type": "array", "items": { "type": "string" } } + }, + "required": ["package", "kind", "name", "targets"] + }, + "node": { + "type": "object", + "properties": { + "id": { "$ref": "#/$defs/nodeID" }, + "catalog": { "$ref": "#/$defs/catalog" }, + "locked": { "type": "string" }, + "eligible": { "type": "string" }, + "latest": { "type": "string" }, + "dependencies": { "type": "array", "items": { "$ref": "#/$defs/edge" } }, + "availableMembers": { "type": "array", "items": { "$ref": "#/$defs/member" } } + }, + "required": ["id", "catalog", "eligible", "dependencies"] + }, + "edge": { + "type": "object", + "properties": { + "target": { "$ref": "#/$defs/nodeID" }, + "requirement": { "type": "string" } + }, + "required": ["target", "requirement"] + }, + "member": { + "type": "object", + "properties": { + "id": { "type": "string" }, + "kind": { "$ref": "#/$defs/memberKind" }, + "name": { "type": "string" } + }, + "required": ["id", "kind", "name"] + }, + "memberKind": { "enum": ["skills", "instructions", "mcpServer"] } + } +} diff --git a/Documentation/Reference/Schemas/mcp-registry-page.schema.json b/Documentation/Reference/Schemas/mcp-registry-page.schema.json new file mode 100644 index 0000000..cd69030 --- /dev/null +++ b/Documentation/Reference/Schemas/mcp-registry-page.schema.json @@ -0,0 +1,23 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "MCP registry search page, version 1", + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "servers": { + "type": "array", + "items": { + "$ref": "mcp-registry-server.schema.json" + } + }, + "nextCursor": { + "type": "string" + } + }, + "required": [ + "schemaVersion", + "servers" + ] +} diff --git a/Documentation/Reference/Schemas/mcp-registry-server.schema.json b/Documentation/Reference/Schemas/mcp-registry-server.schema.json new file mode 100644 index 0000000..4340a89 --- /dev/null +++ b/Documentation/Reference/Schemas/mcp-registry-server.schema.json @@ -0,0 +1,86 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "MCP registry server, version 1", + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "name": { + "type": "string" + }, + "version": { + "type": "string" + }, + "description": { + "type": "string" + }, + "choices": { + "type": "array", + "items": { + "type": "object", + "properties": { + "number": { + "type": "integer", + "minimum": 1 + }, + "transport": { + "type": "string" + }, + "source": { + "type": "string" + }, + "inputs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "required": { + "type": "boolean" + }, + "secret": { + "type": "boolean" + }, + "choices": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "name", + "required", + "secret", + "choices" + ] + } + }, + "unavailable": { + "type": "string" + }, + "requiresPackageCommand": { + "type": "boolean" + } + }, + "required": [ + "number", + "transport", + "source", + "inputs", + "requiresPackageCommand" + ] + } + } + }, + "required": [ + "schemaVersion", + "name", + "version", + "description", + "choices" + ] +} diff --git a/Documentation/Reference/Schemas/mcp-test.schema.json b/Documentation/Reference/Schemas/mcp-test.schema.json new file mode 100644 index 0000000..452b8ff --- /dev/null +++ b/Documentation/Reference/Schemas/mcp-test.schema.json @@ -0,0 +1,70 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Explicit MCP test, version 1", + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "kind": { + "const": "mcp-test" + }, + "transport": { + "enum": [ + "stdio", + "streamableHTTP", + "sse" + ] + }, + "outcome": { + "enum": [ + "discovered", + "noTools", + "incomplete", + "failed" + ] + }, + "issue": { + "type": "string" + }, + "negotiatedVersion": { + "type": "string" + }, + "cleanupComplete": { + "type": "boolean" + }, + "elapsed": { + "type": "number", + "minimum": 0 + }, + "tools": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "title": { + "type": "string" + }, + "description": { + "type": "string" + } + }, + "required": [ + "name" + ] + } + } + }, + "required": [ + "schemaVersion", + "kind", + "transport", + "outcome", + "cleanupComplete", + "elapsed", + "tools" + ] +} diff --git a/Documentation/Reference/Schemas/update.schema.json b/Documentation/Reference/Schemas/update.schema.json index c8165db..205fd5c 100644 --- a/Documentation/Reference/Schemas/update.schema.json +++ b/Documentation/Reference/Schemas/update.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Skill and instruction update preview, version 2", + "title": "Component update preview, version 2", "type": "object", "properties": { "schemaVersion": { @@ -111,6 +111,44 @@ "lockMissing": { "type": "boolean", "description": "Combined preview: no resolved state existed when preparation began." + }, + "components": { + "type": "array", + "items": { + "$ref": "components.schema.json#/$defs/change" + } + }, + "marketplaceChanges": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "before": { + "$ref": "#/$defs/packageRelease" + }, + "after": { + "$ref": "#/$defs/packageRelease" + } + }, + "required": [ + "name" + ], + "anyOf": [ + { + "required": [ + "before" + ] + }, + { + "required": [ + "after" + ] + } + ] + } } }, "required": [ @@ -203,6 +241,28 @@ ] } ] + }, + "packageRelease": { + "type": "object", + "properties": { + "package": { + "type": "string" + }, + "version": { + "type": "string" + }, + "archiveDigest": { + "type": "string" + }, + "catalogCommit": { + "type": "string" + } + }, + "required": [ + "package", + "version", + "archiveDigest" + ] } } } diff --git a/Package.resolved b/Package.resolved index 3ed545f..c4214d4 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,13 +1,22 @@ { - "originHash" : "586b1f666f366ef83112773c577dff68045cc8c33f80d0d3326da317163ec154", + "originHash" : "8da077cf245d6fbebc8831b63b38cc6354f159c9999e2a161197b12048635975", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "65df60ef97ff6d347b6944372a1b75de919313fe", - "version" : "0.2.0" + "revision" : "ce6640adeb53ce0152134547938a6e13472e28b5", + "version" : "0.3.1" + } + }, + { + "identity" : "eventsource", + "kind" : "remoteSourceControl", + "location" : "https://github.com/mattt/eventsource.git", + "state" : { + "revision" : "bb4b61273b5a976bb571859c17f903ebc3439df1", + "version" : "1.6.0" } }, { @@ -19,6 +28,24 @@ "version" : "1.8.2" } }, + { + "identity" : "swift-asn1", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-asn1.git", + "state" : { + "revision" : "917b472dbe53ba699cbb0495f9a95a084bc6364d", + "version" : "1.7.4" + } + }, + { + "identity" : "swift-atomics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-atomics.git", + "state" : { + "revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34", + "version" : "1.3.1" + } + }, { "identity" : "swift-cmark", "kind" : "remoteSourceControl", @@ -28,6 +55,33 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections.git", + "state" : { + "revision" : "88754449ab766a739610b660e117762115fabc9c", + "version" : "1.7.6" + } + }, + { + "identity" : "swift-crypto", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-crypto.git", + "state" : { + "revision" : "f8fad2f95ad67b45f6340c0960e2396094d67e07", + "version" : "5.1.1" + } + }, + { + "identity" : "swift-log", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-log.git", + "state" : { + "revision" : "e3da04078777e6a1b72ce19981fbd6539b0847d8", + "version" : "1.17.0" + } + }, { "identity" : "swift-markdown", "kind" : "remoteSourceControl", @@ -37,6 +91,42 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-nio", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio.git", + "state" : { + "revision" : "2f58d8ef84438d6517fc78bcea2f8527e3c72936", + "version" : "2.105.0" + } + }, + { + "identity" : "swift-sdk", + "kind" : "remoteSourceControl", + "location" : "https://github.com/modelcontextprotocol/swift-sdk.git", + "state" : { + "revision" : "a0ae212ebf6eab5f754c3129608bc5557637e605", + "version" : "0.12.1" + } + }, + { + "identity" : "swift-system", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-system.git", + "state" : { + "revision" : "640e5755b5826f4437eaeedd366fd776737db62c", + "version" : "1.9.0" + } + }, + { + "identity" : "tree-sitter", + "kind" : "remoteSourceControl", + "location" : "https://github.com/tree-sitter/tree-sitter", + "state" : { + "revision" : "da6fe9beb4f7f67beb75914ca8e0d48ae48d6406", + "version" : "0.25.10" + } + }, { "identity" : "yams", "kind" : "remoteSourceControl", diff --git a/Package.swift b/Package.swift index 4a9a622..81edb7d 100644 --- a/Package.swift +++ b/Package.swift @@ -8,7 +8,9 @@ let package = Package( products: [.executable(name: "agents", targets: ["CLI"])], dependencies: [ .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), - .package(url: "https://github.com/agents-tools/core.git", "0.2.0"..<"0.3.0"), + .package( + url: "https://github.com/agents-tools/core.git", + "0.3.1"..<"0.4.0"), ], targets: [ .executableTarget( @@ -16,11 +18,16 @@ let package = Package( dependencies: [ .product(name: "ArgumentParser", package: "swift-argument-parser"), .product(name: "AgentsCore", package: "core"), + .product(name: "AgentsManifest", package: "core"), .product(name: "AgentsSkills", package: "core"), .product(name: "AgentsInstructions", package: "core"), .product(name: "AgentsUpdates", package: "core"), ]), - .testTarget(name: "CLITests", dependencies: ["CLI"]), + .testTarget( + name: "CLITests", + dependencies: [ + "CLI", .product(name: "AgentsManifest", package: "core"), + ]), ], swiftLanguageModes: [.v6] ) diff --git a/README.md b/README.md index 7bf097e..e904a36 100644 --- a/README.md +++ b/README.md @@ -7,13 +7,13 @@

agents

- Install and update agent skills and instructions, resolved to exact versions. + Manage agent components from declared sources, resolved to exact versions.

CI Swift 6.3+ - Platforms: macOS 15+ + Platforms: macOS 15+ and Linux License: MIT

@@ -30,9 +30,9 @@ ## Overview -Declare skills and instruction sections once, restore their locked content with -`install`, and preview upstream changes before applying an update. `agents` -supports Codex, Claude Code, Cursor, Gemini CLI, and OpenCode through +Declare skills, instructions, commands, subagents, MCP servers and settings once, +restore their locked content with `install`, and preview changes before applying +an update. `agents` supports Codex, Claude Code, Cursor, Gemini CLI, OpenCode, and Antigravity through [agents-tools/core](https://github.com/agents-tools/core). The executable owns commands and terminal presentation. Core owns source @@ -54,7 +54,7 @@ an upstream change: ## Install -Versions 0.1.2 and later and development builds require macOS 15 or later. +On macOS, versions 0.1.2 and later and development builds require macOS 15 or later. Earlier releases retain their original requirements. Install the latest release from the Homebrew tap: @@ -73,7 +73,7 @@ brew install --HEAD agents-tools/tap/agents See the [tap documentation](https://github.com/agents-tools/homebrew-tap#readme) for packaging and channel details. -To build from source instead: +To build from source on macOS or Linux: ```sh git clone https://github.com/agents-tools/cli.git @@ -82,8 +82,7 @@ swift build -c release .build/release/agents --help ``` -Place `.build/release/agents` in a directory on your `PATH`. To run from this -checkout, use `.build/release/agents` or `swift run agents`. +To run from this checkout, use `.build/release/agents` or `swift run agents`. ## Usage @@ -108,8 +107,21 @@ agents update --apply agents skills remove pdf agents skills init my-skill agents doctor --root /path/to/project-a /path/to/project-b --json +agents manifest dump --json +agents components list --json +agents components list /path/to/source --alias team --group tools --json +agents components add /path/to/source --alias team --group tools +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 ``` +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) +uses a versioned YAML mapping. `agents manifest dump --json` prints the +local declaration as a JSON object with source locations without resolving sources. + Project scope is the default and uses the current directory. User scope is selected with `--scope user`. Commands never prompt for confirmation. @@ -122,22 +134,36 @@ Instructions are Markdown files with front matter, discovered in a source's `.agent/instructions/` as source `.`. Each agent file is generated from its sections, a section with `paths` goes to the nested file of the directory its patterns share, and Claude is forwarded where needed. A file that agents did not -generate is taken over only with `--replace`. `--agent` on instructions add, -remove, or update sets the recipients of the scope's entire section list. +generate is taken over only with `--replace`. Use `--agent antigravity` on `instructions add` to install one Markdown rule +per selected section in `.agents/rules/` (project) or `~/.gemini/config/rules/` (user). `agents instructions init ` creates `.agent/instructions/.md`, and `agents instructions export` maps locked targets to their sections. -Named ChatGPT prompts are declared in `agents.json` and locked with +Named ChatGPT prompts are declared in `agents.yaml` and locked with `agents instructions update --apply`; render emits only their locked sections and optional custom content. Updates identify changed prompts to re-paste. -Top-level `update` previews skills and instructions together and applies them in -one transaction. `install` and `doctor` process skills then instructions. -All three support combined `--json` reports. +Top-level `update` previews all declared components and applies them in one +transaction. `install` restores the exact locked components in one transaction; +`doctor` audits managed deployments without recovery or writes. All three +support combined `--json` reports. + +`components list` inspects current components or discovers an exported source +group. `components add` applies that group; `components remove` uses an exact +managed identity and optional occurrence when names are ambiguous. Producer-owned +members remain editable at their declaring source. `import` previews an explicit +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) +for supported profiles, selection options and report schemas. ## Requirements -- macOS 15 or later. +- macOS 15 or later, or Linux (source build). - Swift 6.3 or later to build from source. +- SQLite 3 headers and library for Linux source builds (`libsqlite3-dev` on Ubuntu). - Git for Git-backed sources. ## Documentation @@ -159,7 +185,16 @@ then follow the repository's [contributing guide](CONTRIBUTING.md) and ```sh swift build -env -u CODEX_HOME -u CLAUDE_CONFIG_DIR -u XDG_CONFIG_HOME -u XDG_STATE_HOME -u XDG_CACHE_HOME swift test +python3 - <<'PYTEST' +import os, subprocess, tempfile +with tempfile.TemporaryDirectory(prefix="agents-test-home-") as test_home: + environment = {key: value for key, value in os.environ.items() + if key not in ("CODEX_HOME", "CLAUDE_CONFIG_DIR") + and not key.startswith(("XDG_", "GIT_"))} + environment.update(HOME=test_home, GIT_CONFIG_NOSYSTEM="1", + GIT_CONFIG_GLOBAL="/dev/null") + subprocess.run(["swift", "test"], env=environment, check=True) +PYTEST swift build -c release swift format lint --strict --configuration .swift-format --recursive Package.swift Sources Tests ``` @@ -168,13 +203,14 @@ Executable tests create local Git sources and isolated homes in the system temporary directory. Every child process uses an explicit environment rather than inheriting agent or Git configuration. Fixtures are removed after tests. -Core uses the published version range `"0.2.0"..<"0.3.0"`. To use a local core -worktree without changing the package manifest: +Core is pinned to an exact development revision in `Package.swift` and +`Package.resolved`. To use an authorized local core worktree without changing +the package manifest: ```sh swift package resolve swift package edit core --path /path/to/core-worktree -swift test +# Run the isolated test command above. swift package unedit core ``` @@ -194,8 +230,11 @@ declared in the organization's | `policy / policy` | Conventional Commit subjects, PR title, and added-line policy | | `validate / result` | Strict format lint, package tests, release build, and terminal recording check | -[Package configuration](.github/swift-package.json) selects only Xcode 26.6 on -`macos-26`, whose Swift 6.3 matches the package's minimum tools version. +[Package configuration](.github/swift-package.json) selects Xcode 26.6 on +`macos-26` and a pinned Swift 6.4.1 Noble container image for Linux validation. +The Linux job installs the SQLite development package and runs the CLI suite +as the checkout owner. +[Package.swift](Package.swift) defines the minimum toolchain and macOS versions. Formatting uses the default paths: `Package.swift`, `Sources`, and `Tests`. Executable tests cover help, version, and usage errors in an isolated environment. diff --git a/Sources/CLI/AuditCommand.swift b/Sources/CLI/AuditCommand.swift new file mode 100644 index 0000000..bbc3dc1 --- /dev/null +++ b/Sources/CLI/AuditCommand.swift @@ -0,0 +1,105 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct AuditCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "audit", abstract: "Inspect local agent prompts for content integrity.", + discussion: """ + Scan the selected scope, or use --file to inspect one file in that scope. + Use --file with --strip to preview deletions. Add --apply to write them. + """) + + enum Format: String, CaseIterable, ExpressibleByArgument { + case markdown, json, sarif + + var reportFormat: ContentAuditReportFormat { + switch self { + case .markdown: .markdown + case .json: .json + case .sarif: .sarif + } + } + } + + @OptionGroup var location: ScopeOptions + @Option(help: "Inspect this file within the selected scope.") var file: String? + @Option( + help: "Limit scope discovery to this client. Repeat for multiple clients.", + transform: AgentID.parse) + var agent: [AgentID] = [] + @Flag(help: "Fail on critical findings. Advisory findings pass.") var ci = false + @Option(help: "Scan report format. Default: markdown.") var format: Format? + @Flag(help: "Preview deletions from one regular text prompt.") var strip = false + @Flag(help: "Write the deletions from this invocation's strip preview.") var apply = false + + func validate() throws { + if file != nil && !agent.isEmpty { + throw ValidationError("--agent filters scope discovery and cannot be used with --file") + } + if apply && !strip { + throw ValidationError("--apply requires --strip") + } + if strip && (file == nil || ci || format != nil) { + throw ValidationError("--strip requires --file and cannot be used with --ci or --format") + } + } + + func run() throws { + let environment = RuntimeEnvironment() + let report: ContentAuditReport + if let file { + let url = URL(fileURLWithPath: file, relativeTo: environment.projectDirectory).absoluteURL + if strip { + try runStrip(file: url, environment: environment) + return + } + report = ContentAuditOperations.scan( + file: url, scope: location.scope, environment: environment) + } else { + let agents = Set(agent.isEmpty ? AgentID.allCases : agent) + report = ContentAuditOperations.scan( + scope: location.scope, agents: agents, environment: environment) + } + var data = try report.export((format ?? .markdown).reportFormat) + if data.last != 0x0a { data.append(0x0a) } + try FileHandle.standardOutput.write(contentsOf: data) + let status = ci ? report.ciExitCode : report.scanExitCode + if status != 0 { throw ExitCode(status) } + } + + private func runStrip(file: URL, environment: RuntimeEnvironment) throws { + let preview: ContentAuditStripPreview + do { + preview = try ContentAuditOperations.previewStrip( + file: file, scope: location.scope, environment: environment) + } catch ContentAuditStripError.outsideScope { + Terminal.error( + ContentAuditReason.outsideScope.message, remedy: "Choose a file within the selected scope") + throw ExitCode.failure + } catch ContentAuditStripError.unsupportedFile { + Terminal.error( + "This file cannot be stripped", remedy: "Choose a regular UTF-8 Markdown or text prompt") + throw ExitCode.failure + } + + guard !preview.edits.isEmpty else { + Terminal.write("No characters to remove.\n") + return + } + Terminal.write("Proposed deletions in \(location.paths.path(preview.file.path))\n") + for edit in preview.edits { + let codePoint = String(format: "U+%04X", edit.codePoint) + Terminal.write( + " \(edit.line):\(edit.column) \(codePoint) (\(edit.severity.rawValue)) \(edit.reason.message)\n" + ) + } + if apply { + try ContentAuditOperations.applyStrip(preview) + Terminal.write("Applied \(preview.edits.count) deletions.\n") + } else { + Terminal.write("Run again with --apply to write the deletions.\n") + } + } +} diff --git a/Sources/CLI/AuthCommand.swift b/Sources/CLI/AuthCommand.swift new file mode 100644 index 0000000..4f2fe5e --- /dev/null +++ b/Sources/CLI/AuthCommand.swift @@ -0,0 +1,148 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import ArgumentParser +import Foundation + +struct AuthCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "auth", abstract: "Inspect or explicitly export package source credentials.", + subcommands: [Check.self, Export.self]) + + struct Check: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "check", abstract: "Report package source credential status.", + discussion: + "Choose either --source or --host. By default, inspection makes no network requests.") + + @Option( + help: ArgumentHelp( + "Resolve this install selector in the selected scope.", valueName: "selector")) + var source: String? + @Option( + help: ArgumentHelp( + "Inspect host-wide configuration. The default port is 443.", valueName: "host[:port]"), + transform: parseAuthority) + var host: SourceAuthority? + @OptionGroup var location: ScopeOptions + @Flag( + name: .customLong("validate"), + help: "Request validation at the source's authorized provider endpoint. Requires --source.") + var validateCredential = false + @Flag(help: "Write the credential status report as JSON.") var json = false + + func validate() throws { + guard (source != nil) != (host != nil) else { + throw ValidationError("Choose exactly one of --source and --host") + } + if validateCredential && source == nil { + throw ValidationError("--validate requires --source") + } + } + + func run() throws { + let environment = RuntimeEnvironment() + let status: SourceCredentialReport + if let host { + status = try SourceCredentialOperations.inspect(host: host, environment: environment) + } else if let source { + let context = try ScopedSource(scope: location.scope, environment: environment) + if validateCredential { + status = try SourceCredentialOperations.validate( + source: source, declaration: context.declaration, environment: environment, + policy: context.policy) + } else { + status = try SourceCredentialOperations.inspect( + source: source, declaration: context.declaration, environment: environment, + policy: context.policy) + } + } else { + throw ValidationError("Choose exactly one of --source and --host") + } + + if json { + try Terminal.json(CheckReport(status, scope: host == nil ? location.scope : nil)) + } else { + Terminal.write("Provider \(status.provider?.rawValue ?? "unclassified")\n") + Terminal.write("Transport \(status.transport.rawValue)\n") + if let host = status.effectiveHost { + Terminal.write("Effective host \(Terminal.line(host))\n") + } + Terminal.write("Credential source \(status.credentialSource?.rawValue ?? "none")\n") + Terminal.write("Availability \(status.availability.rawValue)\n") + Terminal.write("Validation \(status.validation?.rawValue ?? "skipped")\n") + } + if status.validation == .refused + || (status.transport != .local + && (status.availability == .unavailable || status.availability == .unconfigured)) + { + throw ExitCode.failure + } + } + } + + struct Export: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "export", + abstract: "Write one explicitly exportable source credential to a pipe.", + discussion: + "Use a trusted pipe recipient. The recipient controls what happens to the credential.") + + @Option( + help: ArgumentHelp( + "Resolve this install selector in the selected scope.", valueName: "selector")) + var source: String + @OptionGroup var location: ScopeOptions + + func run() throws { + let environment = RuntimeEnvironment() + let context = try ScopedSource(scope: location.scope, environment: environment) + try SourceCredentialOperations.export( + source: source, declaration: context.declaration, environment: environment, + policy: context.policy) + } + } + + private struct ScopedSource { + let declaration: Declaration + let policy: EffectiveSourcePolicy + + init(scope: InstallScope, environment: RuntimeEnvironment) throws { + declaration = try StateStore(scope: scope, environment: environment).loadDeclaration() + policy = try SourcePolicyOperations.inspect(scope: scope, environment: environment).effective + } + } + + private struct CheckReport: Encodable { + let schemaVersion = 1 + let scope: InstallScope? + let provider: SourceProvider? + let effectiveHost: String? + let transport: SourceCredentialReport.Transport + let credentialSource: SourceCredentialBinding.Category? + let availability: SourceCredentialReport.Availability + let validation: SourceCredentialReport.Validation? + + init(_ status: SourceCredentialReport, scope: InstallScope?) { + self.scope = scope + provider = status.provider + effectiveHost = status.effectiveHost + transport = status.transport + credentialSource = status.credentialSource + availability = status.availability + validation = status.validation + } + } + + private static func parseAuthority(_ input: String) throws -> SourceAuthority { + let invalid = ValidationError("--host requires HOST[:PORT]") + guard !input.contains("%"), !input.hasSuffix(":"), + let parts = URLComponents(string: "https://\(input)", encodingInvalidCharacters: false), + let host = parts.host, parts.user == nil, parts.password == nil, parts.path.isEmpty, + parts.query == nil, parts.fragment == nil, + parts.rangeOfPort == nil || parts.port != nil, + let authority = try? SourceAuthority(host: host, port: parts.port ?? 443) + else { throw invalid } + return authority + } +} diff --git a/Sources/CLI/AuthorPackageCommands.swift b/Sources/CLI/AuthorPackageCommands.swift new file mode 100644 index 0000000..d20c697 --- /dev/null +++ b/Sources/CLI/AuthorPackageCommands.swift @@ -0,0 +1,116 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct CreateAuthorProject: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "init", abstract: "Create an author project with a starter skill.") + @Argument(help: "New project directory.") var directory: String + @Option(help: "Package name.") var name: String + @Option(help: "Release version.") var packageVersion: String + + func run() throws { + let url = URL(fileURLWithPath: directory) + try AuthorPackageOperations.scaffold(.init(name: name, version: packageVersion), at: url) + Terminal.write( + Terminal.line(url.appendingPathComponent(AuthorPackageOperations.specificationFilename).path) + + "\n") + } +} + +struct PackAuthorProject: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "pack", abstract: "Review and package the current author project.") + @Option(help: "Write the reviewed package to a portable archive.") var output: String? + @Option(help: "Publish to a local marketplace directory.") var publishTo: String? + @Option(help: "Require the SHA-256 digest from an earlier review.") var reviewedDigest: String? + + func validate() throws { + if publishTo != nil && output != nil { + throw ValidationError("Choose --output or --publish-to") + } + if publishTo != nil && reviewedDigest == nil { + throw ValidationError("Run bundle pack, then supply its digest with --reviewed-digest") + } + } + + func run() throws { + let artifact: AuthorPackageArtifact + if let reviewedDigest { + artifact = try AuthorPackageOperations.rebuild(expectedDigest: reviewedDigest) + } else { + artifact = try AuthorPackageOperations.preview() + } + Terminal.write( + Terminal.line(artifact.inspection.package.name + "@" + artifact.inspection.package.version) + + "\n") + for member in artifact.inspection.components { + Terminal.write(" " + member.kind.rawValue + " " + Terminal.line(member.name) + "\n") + } + for path in artifact.includedPaths { + Terminal.write(" " + Terminal.line(path.member.name + " / " + path.entry.path) + "\n") + } + writeAuthorFindings(artifact.warnings, artifact.contentFindings, artifact.policyFindings) + Terminal.write("Digest " + artifact.digest + "\n") + if let output { + try AuthorPackageOperations.write(artifact, to: URL(fileURLWithPath: output)) + } else if let publishTo { + try AuthorPackageOperations.publish(artifact, to: URL(fileURLWithPath: publishTo)) + } + } +} + +struct ExportNativePlugin: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "plugin", abstract: "Preview or export a native plugin from the author project.") + @Option(help: "Native client format.") var target: String + @Option(help: "Generate a one-plugin marketplace with this name.") var marketplace: String? + @Option(help: "Category for a Codex marketplace listing.") var category: String? + @Option(help: "Write the distribution to a new directory.") var output: String? + @Option(help: "Require the native tree digest from an earlier review.") var reviewedDigest: + String? + + func run() throws { + guard let target = NativePluginTarget(rawValue: target) else { + throw ValidationError( + "Choose a format: " + NativePluginTarget.allCases.map(\.rawValue).joined(separator: ", ")) + } + if category != nil && (target != .codex || marketplace == nil) { + throw ValidationError("--category requires --target codex and --marketplace") + } + if target == .codex && marketplace != nil && category == nil { + throw ValidationError("Supply --category for the Codex marketplace listing") + } + let plugin = try NativePluginOperations.preview( + AuthorPackageOperations.preview(), for: target, + marketplace: marketplace.map { NativePluginMarketplace(name: $0, category: category) }) + for entry in plugin.entries { Terminal.write(Terminal.line(entry.path) + "\n") } + writeAuthorFindings(plugin.warnings, plugin.contentFindings, plugin.policyFindings) + Terminal.write("Digest " + plugin.digest + "\n") + if let reviewedDigest, reviewedDigest != plugin.digest { + throw ValidationError("The plugin differs from the reviewed tree. Review it again.") + } + if let output { + try NativePluginOperations.write( + plugin, to: URL(fileURLWithPath: output), expectedDigest: reviewedDigest) + } + } +} + +private func writeAuthorFindings( + _ warnings: [AuthorPackageWarning], _ content: [ContentAuditFinding], + _ policy: [OrganizationPolicyFinding] +) { + for warning in warnings { + Terminal.write( + " " + Terminal.line(warning.member.name) + " · " + + warning.reason.rawValue + " (" + String(warning.count) + ")\n") + } + for finding in content { + Terminal.write(" " + Terminal.line(finding.location.path + " · " + finding.message) + "\n") + } + for finding in policy { + Terminal.write(" " + Terminal.line(finding.identity + " · " + finding.message) + "\n") + } +} diff --git a/Sources/CLI/BindingOptions.swift b/Sources/CLI/BindingOptions.swift new file mode 100644 index 0000000..dadaf2d --- /dev/null +++ b/Sources/CLI/BindingOptions.swift @@ -0,0 +1,63 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct BindingOptions: ParsableArguments { + @Option( + name: .long, + help: + "Supply a runtime binding from NAME=ENV_VAR. Repeat for several; values are read only when applying or testing." + ) + var binding: [String] = [] + + func validate() throws { _ = try provider() } + + func provider() throws -> EnvironmentBindings { + try EnvironmentBindings(variables: Self.mappings(binding, option: "--binding")) + } + + static func mappings(_ binding: [String], option: String) throws -> [String: String] { + guard binding.count <= 256 else { throw ValidationError("At most 256 bindings are supported") } + var variables: [String: String] = [:] + for mapping in binding { + let parts = mapping.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) + guard parts.count == 2, !parts[0].isEmpty, !parts[1].isEmpty, + mapping.utf8.count <= 4096, + !mapping.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains), + !parts[1].contains("="), variables[String(parts[0])] == nil + else { throw ValidationError("Use distinct \(option) NAME=ENV_VAR mappings") } + variables[String(parts[0])] = String(parts[1]) + } + return variables + } +} + +struct EnvironmentBindings: RuntimeBindingProvider { + let variables: [String: String] + + func value(for binding: String, environment: RuntimeEnvironment) throws -> Data { + guard let variable = variables[binding], let value = environment.environment[variable] else { + throw CoreError.invalidState("runtime binding unavailable: \(binding)") + } + guard value.utf8.count <= 1_048_576, !value.utf8.contains(0) else { + throw CoreError.invalidState("runtime binding invalid: \(binding)") + } + return Data(value.utf8) + } +} + +struct ComponentWriteOptions: ParsableArguments { + @OptionGroup var bindings: BindingOptions + @Flag(help: "Replace conflicting content where Core supports explicit takeover.") var replace = + false + @Flag(help: "Allow Core's reported owner-only permission change for private materialization.") + var changingAccess = false + + func request(_ request: UpdateRequest = UpdateRequest()) -> UpdateRequest { + var request = request + request.replace = replace + request.changingAccess = changingAccess + return request + } +} diff --git a/Sources/CLI/BundleCommands.swift b/Sources/CLI/BundleCommands.swift new file mode 100644 index 0000000..831f549 --- /dev/null +++ b/Sources/CLI/BundleCommands.swift @@ -0,0 +1,140 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct BundleCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "bundle", abstract: "Share selected instructions, skills and MCP servers.", + subcommands: [ + CreateAuthorProject.self, PackAuthorProject.self, ExportNativePlugin.self, + ExportBundle.self, InspectBundle.self, ImportBundle.self, + ]) +} + +struct ExportBundle: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "export", abstract: "Write a portable archive of selected locked components.") + @Argument(help: "Destination archive path.") var output: String + @Option(help: "Package name.") var name: String + @Option(help: "Package version.") var packageVersion: String + @Option(help: "Component identity from components list --json. Repeat to combine components.") + var component: [String] + @Option(help: "Require [CATALOG:]PACKAGE@REQUIREMENT. Repeat for multiple packages.") + var dependency: [String] = [] + @OptionGroup var location: ScopeOptions + + func run() throws { + let inspection = try UpdateOperations.inspect(scope: location.scope) + try requireCommittedInspection(inspection) + let selected = try component.map { identity in + let matches = inspection.components.filter { $0.selection.identity == identity } + guard matches.count == 1, let item = matches.first else { + throw ValidationError("Unknown or ambiguous component identity: " + Terminal.line(identity)) + } + return item.selection + } + let dependencies = try dependency.map { value in + let fields = value.split(separator: "@", maxSplits: 1, omittingEmptySubsequences: false) + guard fields.count == 2 else { + throw ValidationError("--dependency expects [CATALOG:]PACKAGE@REQUIREMENT") + } + let reference = try MarketplacePackageReference(String(fields[0]), scope: location.scope) + return try MarketplacePackageRequirement( + package: reference.package, requirement: parseMarketplaceRequirement(String(fields[1])), + catalog: reference.catalog) + } + let data = try BundleOperations.export( + BundlePackage(name: name, version: packageVersion, dependencies: dependencies), + selections: selected, + scope: location.scope, environment: RuntimeEnvironment()) + try data.write(to: URL(fileURLWithPath: output), options: .withoutOverwriting) + } +} + +struct InspectBundle: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "inspect", abstract: "Verify a package and list its selectable components.") + @Argument(help: "Portable archive path.") var file: String + + func run() throws { + let bundle = try BundleOperations.inspect(Data(contentsOf: URL(fileURLWithPath: file))) + Terminal.write( + "\(Terminal.line(bundle.package.name)) \(Terminal.line(bundle.package.version))\n") + for dependency in bundle.package.dependencies ?? [] { + let catalog = dependency.catalog.map { " \(Terminal.line($0.location))" } ?? "" + Terminal.write( + "Requires \(Terminal.line(dependency.package)) \(MarketplaceOutput.requirement(dependency.requirement))\(catalog)\n" + ) + } + for component in bundle.components { + Terminal.write( + "\(Terminal.line(component.id)) \(component.kind.rawValue) \(Terminal.line(component.name))\n" + ) + } + } +} + +struct ImportBundle: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "import", abstract: "Preview or apply selected archive entries to clients.") + @Argument(help: "Portable archive path.") var file: String + @OptionGroup var installation: BundleInstallOptions + + func run() async throws { + let bundle = try BundleOperations.inspect(Data(contentsOf: URL(fileURLWithPath: file))) + let selections = installation.selections(in: bundle) + let options = installation.options + let scope = options.location.scope + let environment = RuntimeEnvironment() + if options.apply { + let review = try BundleOperations.previewImportLifecycle( + bundle, selections: selections, intent: .install, scope: scope, + environment: environment, replace: installation.replace) + try await options.applyImport(review, bindings: installation.bindings) + } else { + let preview = try BundleOperations.previewImport( + bundle, selections: selections, scope: scope, environment: environment, + replace: installation.replace) + try options.showImport(preview) + } + } +} + +struct BundleInstallOptions: ParsableArguments { + @Option(help: "Entry ID from bundle inspect. Omit to include the whole package.") + var component: [String] = [] + @Option(help: "Destination client. Repeat for multiple clients.", transform: AgentID.parse) + var agent: [AgentID] + @OptionGroup var options: UpdateOptions + @OptionGroup var bindings: BindingOptions + @Flag(help: "Replace conflicting instruction content as shown by the preview.") var replace = + false + + func selections(in bundle: BundleInspection) -> [BundleImportSelection] { + let ids = component.isEmpty ? bundle.components.map(\.id) : component + return ids.map { BundleImportSelection(componentID: $0, targets: agent) } + } +} + +extension UpdateOptions { + func showImport(_ preview: BundleImportPreview) throws { + if json { + try Terminal.json(UpdateReport(preview.report)) + } else { + Terminal.updateDifferences(preview.report, paths: location.paths) + } + if let conflict = preview.ownershipConflict { throw CoreError.invalidState(conflict) } + if !apply && !json { + previewNotice(changed: preview.report.hasChanges) + } + } + + func applyImport( + _ review: LifecyclePackageReview, + bindings: BindingOptions + ) async throws { + try showImport(review.report) + try await applyLifecycle(review, scope: location.scope, bindingProvider: bindings.provider()) + } +} diff --git a/Sources/CLI/CacheCommand.swift b/Sources/CLI/CacheCommand.swift new file mode 100644 index 0000000..006342d --- /dev/null +++ b/Sources/CLI/CacheCommand.swift @@ -0,0 +1,181 @@ +import AgentsCore +import ArgumentParser +import Foundation + +struct CacheCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "cache", abstract: "Inspect and maintain downloaded package data.", + subcommands: [Info.self, Clean.self, Prune.self]) + + struct Info: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "info", abstract: "List cache stores and disk usage.") + @Flag(help: "Print machine-readable inventory.") var json = false + + func run() throws { + let inventory = try AcquisitionCache().inspect() + let stores = AcquisitionCacheStore.allCases.map { kind in + Store( + name: kind.rawValue, entries: inventory.entries.filter { $0.store == kind }.count, + bytes: inventory.bytes(in: kind)) + } + if json { + try Terminal.json( + Inventory( + root: inventory.root.path, totalBytes: inventory.totalBytes, stores: stores, + entries: inventory.entries.map(Entry.init), issues: inventory.issues.map(Issue.init))) + } else { + Terminal.write("Cache: " + Terminal.line(inventory.root.path) + "\n") + for store in stores { + Terminal.write("\(store.name) \(store.entries) entries \(store.bytes) bytes\n") + } + Terminal.write("Total: \(inventory.totalBytes) bytes\n") + writeIssues(inventory.issues) + } + if !inventory.issues.isEmpty { throw ExitCode.failure } + } + } + + struct Clean: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "clean", abstract: "Review or remove disposable cached data.") + @OptionGroup var options: MaintenanceOptions + func run() throws { try options.run(.clean) } + } + + struct Prune: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "prune", abstract: "Review or remove unused Git revisions.") + @Option(help: "Minimum age in days.") var days = 30 + @OptionGroup var options: MaintenanceOptions + func validate() throws { + if days < 0 { throw ValidationError("--days must be nonnegative") } + } + func run() throws { try options.run(.prune(days: days)) } + } + + struct MaintenanceOptions: ParsableArguments { + @Flag( + name: [ + .long, .customLong("force"), .customLong("yes"), .customShort("f"), .customShort("y"), + ], + help: "Remove the selected entries. The default is a read-only preview.") var apply = false + @Flag(help: "Print the preview or removal result as JSON.") var json = false + + func run(_ operation: AcquisitionCacheMaintenance) throws { + let cache = AcquisitionCache() + let preview = try cache.preview(operation) + let name: String + let days: Int? + switch operation { + case .clean: (name, days) = ("clean", nil) + case .prune(let age): (name, days) = ("prune", age) + } + if apply { + let result = try cache.apply(preview) + if json { + try Terminal.json( + Removal( + operation: name, days: days, root: preview.root.path, + reclaimedBytes: result.reclaimedBytes, removed: result.removed.map(Entry.init), + skipped: result.skipped.map(Entry.init), failures: result.failures.map(Issue.init))) + } else { + Terminal.write( + "Removed \(result.removed.count) entries, reclaimed \(result.reclaimedBytes) bytes.\n") + for entry in result.skipped { + Terminal.write( + "Skipped " + Terminal.line(entry.store.rawValue + "/" + entry.id) + "\n") + } + writeIssues(result.failures) + } + if !result.isComplete { throw ExitCode.failure } + } else { + if json { + try Terminal.json( + Preview( + operation: name, days: days, root: preview.root.path, + totalBytes: preview.totalBytes, candidates: preview.candidates.map(Entry.init), + issues: preview.issues.map(Issue.init))) + } else { + Terminal.write("Cache: " + Terminal.line(preview.root.path) + "\n") + for entry in preview.candidates { + Terminal.write( + Terminal.line(entry.store.rawValue + "/" + entry.id) + " \(entry.bytes) bytes\n") + } + Terminal.write( + "Selected \(preview.candidates.count) entries, \(preview.totalBytes) bytes.\n") + if !preview.candidates.isEmpty { + Terminal.write("Run again with --apply to remove eligible entries.\n") + } + writeIssues(preview.issues) + } + if !preview.issues.isEmpty { throw ExitCode.failure } + } + } + } + + private static func writeIssues(_ issues: [AcquisitionCacheIssue]) { + for issue in issues { Terminal.notice(issue.path + ": " + issue.reason) } + } + + private struct Entry: Encodable { + let store: String + let id: String + let object: String + let bytes: Int64 + let lastUsed: String + let pendingDisposal: Bool + init(_ entry: AcquisitionCacheEntry) { + store = entry.store.rawValue + id = entry.id + object = entry.object + bytes = entry.bytes + lastUsed = entry.lastUsed.ISO8601Format() + pendingDisposal = entry.pendingDisposal + } + } + + private struct Issue: Encodable { + let path: String + let reason: String + init(_ issue: AcquisitionCacheIssue) { + path = issue.path + reason = issue.reason + } + } + + private struct Store: Encodable { + let name: String + let entries: Int + let bytes: Int64 + } + private struct Inventory: Encodable { + let schemaVersion = 1 + let root: String + let totalBytes: Int64 + let stores: [Store] + let entries: [Entry] + let issues: [Issue] + } + + private struct Preview: Encodable { + let schemaVersion = 1 + let operation: String + let days: Int? + let root: String + let totalBytes: Int64 + let candidates: [Entry] + let issues: [Issue] + } + + private struct Removal: Encodable { + let schemaVersion = 1 + let operation: String + let days: Int? + let root: String + let reclaimedBytes: Int64 + let removed: [Entry] + let skipped: [Entry] + let failures: [Issue] + } +} diff --git a/Sources/CLI/ComponentCommands.swift b/Sources/CLI/ComponentCommands.swift new file mode 100644 index 0000000..20d6cf8 --- /dev/null +++ b/Sources/CLI/ComponentCommands.swift @@ -0,0 +1,243 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct ComponentsCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "components", + abstract: "Inspect, add and remove managed components.", + subcommands: [ + ListComponents.self, ComponentInventoryCommand.self, AddComponents.self, + RemoveComponents.self, + ]) +} + +struct ComponentInventoryCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "inventory", + abstract: "Export the locked component inventory as CycloneDX or SPDX JSON.") + @OptionGroup var location: ScopeOptions + @Option( + help: "Inventory format: cyclonedx or spdx.", + transform: { value in + guard let format = InventoryFormat(rawValue: value) else { + throw ValidationError("Use cyclonedx or spdx") + } + return format + }) var format: InventoryFormat = .cycloneDX + + func run() throws { + let environment = RuntimeEnvironment() + let date = try environment.environment["SOURCE_DATE_EPOCH"].map { value in + guard let seconds = Int64(value), (0...253_402_300_799).contains(seconds) else { + throw ValidationError( + "SOURCE_DATE_EPOCH must be a nonnegative Unix timestamp through year 9999") + } + return Date(timeIntervalSince1970: TimeInterval(seconds)) + } + let inspection = try UpdateOperations.inspect(scope: location.scope, environment: environment) + let data = try inspection.inventory(format: format, createdAt: date) + try FileHandle.standardOutput.write(contentsOf: data + Data("\n".utf8)) + } +} + +/// Builds canonical group intent; source parsing and graph discovery remain in Core. +struct ComponentSourceOptions: ParsableArguments { + @Option(help: "Group exported by the source.") var group: String? + @Option(help: "Alias for a new source; existing aliases can be used directly.") var alias: String? + @OptionGroup var requirements: RequirementOptions + @OptionGroup var path: SourcePathOptions + + func validate() throws { + if group?.isEmpty == true || alias?.isEmpty == true { + throw ValidationError("Group and source alias must not be empty") + } + } + + func declaration(source: String, inspection: ScopeInspection) throws -> Declaration { + guard var declaration = inspection.declaration, !inspection.recovery.pending else { + throw CoreError.recoveryPending( + inspection.recovery.diagnostic ?? "Transaction recovery is pending") + } + guard let group, !group.isEmpty else { throw ValidationError("A source requires --group") } + let name: String + if declaration.sources[source] != nil { + guard alias == nil || alias == source else { + throw ValidationError("Use the existing source alias directly") + } + name = source + if let requirement = requirements.requirement { + declaration.sources[name]?.requirement = requirement + } + if let path = path.path { declaration.sources[name]?.path = path } + } else { + guard let alias, !alias.isEmpty else { + throw ValidationError("A new source requires --alias") + } + guard declaration.sources[alias] == nil else { + throw ValidationError("Source alias already exists") + } + let environment = RuntimeEnvironment() + let parsed = try SourceParser.parse( + source, currentDirectory: environment.projectDirectory, + homeDirectory: environment.homeDirectory) + name = alias + declaration.sources[name] = SourceDeclaration( + kind: parsed.type, location: parsed.localPath ?? parsed.url, + requirement: requirements.requirement ?? parsed.requirement, + path: path.path ?? parsed.subpath) + } + let use = GroupUseDeclaration(name: group, source: name) + if !declaration.uses.contains(use) { declaration.uses.append(use) } + return declaration + } +} + +struct ListComponents: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "list", + abstract: "Inspect managed components, or discover an exported source group without installing." + ) + @Argument(help: "Source alias, local directory or repository URL to discover.") var source: + String? + @OptionGroup var selection: ComponentSourceOptions + @OptionGroup var location: ScopeOptions + @Flag(help: "Print the versioned JSON report.") var json = false + + func validate() throws { + if source != nil && selection.group == nil { + throw ValidationError("A source requires --group") + } + if source == nil + && (selection.group != nil || selection.alias != nil || selection.path.path != nil + || selection.requirements.requirement != nil) + { + throw ValidationError("Source options require a source argument") + } + } + + func run() throws { + let inspection = try UpdateOperations.inspect(scope: location.scope) + try requireCommittedInspection(inspection) + let components: [ComponentInspection] + if let source { + components = try UpdateOperations.discover( + selection.declaration(source: source, inspection: inspection), scope: location.scope + ).components + } else { + components = inspection.components + } + if json { + try Terminal.json(ComponentListReport(scope: location.scope, components: components)) + } else { + Terminal.componentList(components) + } + } +} + +struct AddComponents: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "add", + abstract: "Declare and apply an exported source group.") + @Argument(help: "Source alias, local directory or repository URL.") var source: String + @OptionGroup var selection: ComponentSourceOptions + @OptionGroup var location: ScopeOptions + @OptionGroup var writing: ComponentWriteOptions + + func validate() throws { + if selection.group == nil { throw ValidationError("Provide --group") } + } + + func run() throws { + let result = try withRecovery { + let inspection = try UpdateOperations.inspect(scope: location.scope) + try requireCommittedInspection(inspection) + let discovered = try UpdateOperations.discover( + selection.declaration(source: source, inspection: inspection), scope: location.scope) + return try UpdateOperations.withPreparedUpdate( + writing.request(discovered.updateRequest()), scope: location.scope, + bindingProvider: writing.bindings.provider() + ) { try $0.apply() } + } + Terminal.updatedSkills(result.report.skills) + Terminal.updatedInstructions(result.report.instructions, paths: location.paths) + Terminal.componentChanges(result.report.components, paths: location.paths, applied: true) + } +} + +struct ComponentSelector: ParsableArguments { + @Argument(help: "Exact managed component name.") var name: String + @Option(help: "Limit to a component kind.", transform: parseComponentKind) var kind: + DeclaredComponentKind? + @Option(help: "Exact logical identity from components list; disambiguates duplicate names.") + var identity: String? + @Option(help: "Exact occurrence ID from components list.") var occurrence: Int? + + func validate() throws { + if let occurrence, occurrence < 0 { + throw ValidationError("Occurrence IDs must be nonnegative") + } + } + + func select(in inspection: ScopeInspection) throws -> ComponentSelection { + try requireCommittedInspection(inspection) + let matches = inspection.components.filter { + $0.name == name && (kind == nil || $0.kind == kind) + && (identity == nil || $0.selection.identity == identity) + && (occurrence == nil || $0.occurrences.contains { $0.selection.occurrence == occurrence }) + } + guard matches.count == 1, let component = matches.first else { + throw CoreError.invalidState( + "component selection is missing or ambiguous; use components list and --kind/--identity") + } + guard let occurrence else { return component.selection } + let occurrences = component.occurrences.filter { $0.selection.occurrence == occurrence } + guard occurrences.count == 1, let selected = occurrences.first else { + throw CoreError.invalidState( + "component occurrence is missing or ambiguous; refresh components list") + } + return selected.selection + } +} + +func parseComponentKind(_ value: String) throws -> DeclaredComponentKind { + guard let kind = DeclaredComponentKind(rawValue: value) else { + throw ValidationError("Unknown component kind") + } + return kind +} + +func requireCommittedInspection(_ inspection: ScopeInspection) throws { + if inspection.recovery.pending { + throw CoreError.recoveryPending( + inspection.recovery.diagnostic ?? "Transaction recovery is pending") + } +} + +struct RemoveComponents: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "remove", abstract: "Remove an exact managed component or occurrence.") + @OptionGroup var selection: ComponentSelector + @OptionGroup var location: ScopeOptions + @OptionGroup var agents: AgentOptions + @OptionGroup var writing: ComponentWriteOptions + + func run() async throws { + let scope = location.scope + let review = try previewAfterRecovery(scope: scope) { + let inspection = try UpdateOperations.inspect(scope: scope) + let selected = try selection.select(in: inspection) + let request = UpdateRequest( + operation: .remove, selections: [selected], agents: agents.recipients) + return try UpdateOperations.previewLifecycle( + writing.request(request), intent: .uninstall, scope: scope) + } + try await applyLifecycle(review, scope: scope, bindingProvider: writing.bindings.provider()) { + result, _ in + Terminal.updatedSkills(result.report.skills) + Terminal.updatedInstructions(result.report.instructions, paths: location.paths) + Terminal.componentChanges(result.report.components, paths: location.paths, applied: true) + } + } +} diff --git a/Sources/CLI/ComponentReports.swift b/Sources/CLI/ComponentReports.swift new file mode 100644 index 0000000..268c9ed --- /dev/null +++ b/Sources/CLI/ComponentReports.swift @@ -0,0 +1,143 @@ +import AgentsCore +import AgentsUpdates +import Foundation + +struct ComponentChangeItem: Encodable { + let kind: String + let name: String + let source: String + let revision: String? + let version: String? + let path: String + let format: String + let ownership: String + let agents: [String] + let changed: Bool + let requiredBindings: [String] + let effectiveReaders: [String] + let privateMaterialization: Bool + let before: String? + let after: String? + let resources: [Resource] + let permissionChange: Permissions? + + struct Resource: Encodable { + let path: String + let hash: String + let executableFiles: [String: Bool] + } + struct Permissions: Encodable { + let beforeOwner: UInt32 + let beforeGroup: UInt32 + let beforeMode: UInt32 + let afterOwner: UInt32 + let afterMode: UInt32 + let ownerOnly: Bool + } + + init(_ change: ComponentUpdateChange) { + kind = change.kind + name = change.name + source = change.sourceIdentity + revision = change.revision + version = change.version + path = change.path + format = change.format + ownership = change.ownership + agents = change.agents.map(\.rawValue) + changed = change.changed + requiredBindings = change.requiredBindings + effectiveReaders = change.effectiveReaders.map(\.rawValue) + privateMaterialization = change.privateMaterialization + before = change.symbolicBefore + after = change.symbolicAfter + resources = change.resources.map { + .init(path: $0.path, hash: $0.hash, executableFiles: $0.executableFiles) + } + permissionChange = change.permissionChange.map { + .init( + beforeOwner: $0.beforeOwner, beforeGroup: $0.beforeGroup, beforeMode: $0.beforeMode, + afterOwner: $0.afterOwner, afterMode: $0.afterMode, ownerOnly: $0.ownerOnly) + } + } +} + +struct ComponentListReport: Encodable { + let schemaVersion = 1 + let kind = "components" + let scope: String + let components: [Item] + + struct Item: Encodable { + let identity: String + let generation: String + let kind: String + let name: String + let source: String + let group: String? + let revision: String? + let agents: [String] + let occurrences: [Occurrence] + } + struct Occurrence: Encodable { + let id: Int? + let source: String + let manifestPath: String + let consumerEditable: Bool + } + + init(scope: InstallScope, components: [ComponentInspection]) { + self.scope = scope.rawValue + self.components = components.map { + .init( + identity: $0.selection.identity, generation: $0.selection.generation, + kind: $0.kind.rawValue, name: $0.name, source: $0.source, group: $0.group, + revision: $0.revision, agents: $0.recipients.map(\.rawValue), + occurrences: $0.occurrences.map { + .init( + id: $0.selection.occurrence, source: $0.declaringSource, + manifestPath: $0.manifestPath, consumerEditable: $0.consumerEditable) + }) + } + } +} + +extension Terminal { + static func componentChanges( + _ components: [ComponentUpdateChange], paths: HumanPaths, applied: Bool + ) { + for component in components { + let verb = applied ? "Applied" : component.changed ? "Change" : "Unchanged" + write( + "\(verb) \(line(component.kind)) \(line(component.name)) in \(paths.path(component.path)) (\(line(component.format))).\n" + ) + if !applied { + if let before = component.symbolicBefore { write(" Before: \(line(before))\n") } + if let after = component.symbolicAfter { write(" After: \(line(after))\n") } + if !component.requiredBindings.isEmpty { + write( + " Required bindings: \(component.requiredBindings.map(line).joined(separator: ", "))\n" + ) + } + if let access = component.permissionChange { + write( + " Permissions: \(String(access.beforeMode, radix: 8)) -> \(String(access.afterMode, radix: 8)); owner \(access.afterOwner).\n" + ) + } + } + } + } + + static func componentList(_ components: [ComponentInspection]) { + if components.isEmpty { write("No components.\n") } + for component in components { + write("\(line(component.kind.rawValue)) \(line(component.name)) \(line(component.source))\n") + write(" Identity: \(line(component.selection.identity))\n") + for occurrence in component.occurrences { + write( + " Occurrence \(occurrence.selection.occurrence.map(String.init) ?? "all"): \(line(occurrence.manifestPath))\n" + ) + } + } + } +} diff --git a/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index aac60de..ec080be 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -1,15 +1,21 @@ +import AgentsCore import ArgumentParser -import Darwin import Foundation +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + enum BuildInfo { - static let version = "0.2.0" + static let version = "0.3.1" } struct Agents: ParsableCommand { static let configuration = CommandConfiguration( commandName: "agents", - abstract: "Manage agent skills and instructions from declared sources.", + abstract: "Manage agent components from declared sources.", discussion: """ Examples: agents skills add github.com/owner/skills pdf-forms @@ -21,7 +27,10 @@ struct Agents: ParsableCommand { agents update --apply Write the updates and the new lock """, subcommands: [ - Skills.self, InstructionsCommand.self, Watch.self, Install.self, Update.self, Doctor.self, + 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, ] ) @@ -43,7 +52,8 @@ struct Skills: ParsableCommand { @main enum EntryPoint { - static func main() { + static func main() async { + ProcessLimits.raiseOpenFileLimit() var command: any ParsableCommand do { let arguments = Array(CommandLine.arguments.dropFirst()) @@ -61,10 +71,14 @@ enum EntryPoint { } Terminal.error( Agents.message(for: error), remedy: "Run 'agents --help' for usage.") - Darwin.exit(64) + exit(64) } do { - try command.run() + if var asynchronous = command as? any AsyncParsableCommand { + try await asynchronous.run() + } else { + try command.run() + } } catch { // Help requests from a command group are successful parser exits. if Agents.exitCode(for: error) == .success { @@ -72,11 +86,11 @@ enum EntryPoint { return } if let code = error as? ExitCode { - Darwin.exit(code.rawValue) + exit(code.rawValue) } Terminal.error( Terminal.failureMessage(error), remedy: Terminal.failureRemedy(error, command: command)) - Darwin.exit(1) + exit(1) } } diff --git a/Sources/CLI/ExportPatchCommand.swift b/Sources/CLI/ExportPatchCommand.swift new file mode 100644 index 0000000..7ac1959 --- /dev/null +++ b/Sources/CLI/ExportPatchCommand.swift @@ -0,0 +1,57 @@ +import AgentsUpdates +import ArgumentParser +import Foundation + +struct ExportPatchCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "export-patch", abstract: "Export local edits as patches for their producers.") + + @OptionGroup var location: ScopeOptions + @Flag(help: "Preview patches and skipped files.") var dryRun = false + @Option( + name: [.customShort("o"), .long], help: "Output directory. Defaults to patches in the project.") + var out: String? + @Flag(help: "Print the review and export result as JSON.") var json = false + + func run() throws { + let preview = try UpdateOperations.previewProducerPatches(scope: location.scope) + let result: ProducerPatchExport? + if dryRun { + result = nil + } else { + result = try UpdateOperations.exportProducerPatches( + preview, to: out.map { URL(fileURLWithPath: $0, isDirectory: true) }) + } + + if json { + try Terminal.json(Report(preview: preview, export: result)) + } else { + for patch in preview.patches { + Terminal.write( + "\(Terminal.line(patch.filename)) \(Terminal.line(patch.producer.source))\n") + for path in patch.paths { Terminal.write(" \(Terminal.line(path))\n") } + } + for skip in preview.skipped { + Terminal.write("Skipped \(location.paths.path(skip.path.path)): \(skip.reason.rawValue)\n") + } + if preview.patches.isEmpty { Terminal.write("No exportable edits.\n") } + if let result { + for file in result.written { Terminal.write("Wrote \(location.paths.path(file.path))\n") } + for file in result.reused { + Terminal.write("Already present: \(location.paths.path(file.path))\n") + } + for failure in result.failures { + Terminal.write( + "Failed \(location.paths.path(failure.file.path)): \(failure.reason.rawValue)\n") + } + } + } + if let result, !result.failures.isEmpty { throw ExitCode.failure } + } + + private struct Report: Encodable { + let schemaVersion = 1 + let preview: ProducerPatchPreview + let export: ProducerPatchExport? + } +} diff --git a/Sources/CLI/ImportCommand.swift b/Sources/CLI/ImportCommand.swift new file mode 100644 index 0000000..6af7fb6 --- /dev/null +++ b/Sources/CLI/ImportCommand.swift @@ -0,0 +1,143 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct ImportCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "import", + abstract: + "Preview an explicit producer document; use --apply to merge and deploy canonical intent.") + @Argument(help: "Document path relative to --root.") var document: String + @Option(help: "Core import profile, for example codexConfigV1 or claudeCommandV1.") var format: + String + @Option(help: "Directory containing the producer document. Default: current directory.") var root: + String = "." + @Option( + name: .long, + help: + "Select a producer member. Repeat for several; interpretation belongs to the import profile.") + var select: [String] = [] + @OptionGroup var writing: ComponentWriteOptions + @OptionGroup var options: UpdateOptions + + func run() throws { + let environment = RuntimeEnvironment() + let directory = URL(fileURLWithPath: root, relativeTo: environment.projectDirectory) + .standardizedFileURL + let imported = try SourceImportOperations.inspect( + format: format, root: directory, + document: document, selection: select.isEmpty ? nil : Set(select)) + if options.apply { + let result = try withRecovery { + let inspection = try UpdateOperations.inspect(scope: options.location.scope) + try requireCommittedInspection(inspection) + let request = try imported.updateRequest(in: inspection) + return try UpdateOperations.withPreparedUpdate( + writing.request(request), scope: options.location.scope, + bindingProvider: writing.bindings.provider() + ) { update in + Terminal.updateDifferences(update.report, paths: options.location.paths) + return try update.apply() + } + } + Terminal.componentChanges( + result.report.components, paths: options.location.paths, applied: true) + Terminal.updatedSkills(result.report.skills) + Terminal.updatedInstructions(result.report.instructions, paths: options.location.paths) + } else { + let report = ImportReport(imported) + if options.json { + try Terminal.json(report) + } else { + Terminal.write( + "Import \(Terminal.line(report.format)): \(report.sources.count) sources, \(report.components.count) components.\n" + ) + for diagnostic in report.diagnostics { + Terminal.write( + " \(Terminal.line(diagnostic.code)) \(Terminal.line(diagnostic.document))\(Terminal.line(diagnostic.pointer)): \(Terminal.line(diagnostic.message))\n" + ) + } + for binding in report.bindings { + Terminal.write( + " Required binding at \(Terminal.line(binding.document))\(Terminal.line(binding.pointer)): \(Terminal.line(binding.reason))\n" + ) + } + Terminal.write("Preview only. Run again with --apply to import.\n") + } + } + } +} + +struct ImportReport: Encodable { + let schemaVersion = 1 + let kind = "import" + let format: String + let producerRevision: String? + let specificationStatus: String + let sources: [Source] + let components: [Component] + let diagnostics: [Diagnostic] + let bindings: [Binding] + let resources: [Resource] + + struct Source: Encodable { + let alias: String + let document: String + let pointer: String + let commit: String? + let version: String? + let developmentOnly: Bool + } + struct Component: Encodable { + let document: String + let pointer: String + let kind: String + } + struct Diagnostic: Encodable { + let code: String + let document: String + let pointer: String + let message: String + } + struct Binding: Encodable { + let document: String + let pointer: String + let reason: String + let environmentVariable: String? + } + struct Resource: Encodable { + let source: String + let path: String? + let hash: String? + let selected: Bool + let requiresStandaloneSource: Bool + } + + init(_ inspection: SourceImportInspection) { + format = inspection.format + producerRevision = inspection.producerRevision + specificationStatus = inspection.specificationStatus + sources = inspection.sources.map { + .init( + alias: $0.alias, document: $0.document, pointer: $0.pointer, + commit: $0.commit, version: $0.version, developmentOnly: $0.developmentOnly) + } + components = inspection.components.map { + .init(document: $0.document, pointer: $0.pointer, kind: $0.declaration.kind.rawValue) + } + diagnostics = inspection.diagnostics.map { + .init(code: $0.code, document: $0.document, pointer: $0.pointer, message: $0.message) + } + bindings = inspection.bindings.map { + .init( + document: $0.document, pointer: $0.pointer, reason: $0.reason, + environmentVariable: $0.environmentVariable) + } + resources = inspection.resources.map { + .init( + source: $0.sourceAlias, path: $0.path, hash: $0.hash, + selected: $0.selected, requiresStandaloneSource: $0.requiresStandaloneSource) + } + } +} diff --git a/Sources/CLI/InstructionCommands.swift b/Sources/CLI/InstructionCommands.swift index 0fd8beb..3427e52 100644 --- a/Sources/CLI/InstructionCommands.swift +++ b/Sources/CLI/InstructionCommands.swift @@ -1,5 +1,7 @@ import AgentsCore import AgentsInstructions +import AgentsManifest +import AgentsUpdates import ArgumentParser import Foundation @@ -18,7 +20,7 @@ struct InstructionAgentOptions: ParsableArguments { @Option( name: .long, help: - "Set recipients of the scope's section list: codex, claude-code, cursor, gemini-cli or opencode. Repeat for several. Default: the recorded instruction agents, else the declaration's agents, else codex and claude-code.", + "Select recipients: codex, claude-code, cursor, gemini-cli, opencode, or antigravity. Repeat for several. Omit to use the configured default recipients.", transform: AgentID.parse) var agent: [AgentID] = [] @@ -29,7 +31,10 @@ struct InstructionAgentOptions: ParsableArguments { struct AddInstructions: ParsableCommand { static let configuration = CommandConfiguration( - commandName: "add", abstract: "Declare and install instruction sections from a source.") + commandName: "add", abstract: "Declare and install instruction sections from a source.", + discussion: + "With --agent antigravity, install the selected sections as rules in the selected scope. Other sections keep their recipients." + ) @Argument( help: @@ -55,29 +60,30 @@ struct AddInstructions: ParsableCommand { source: source, names: names, replace: replace, agents: agents.recipients, scope: location.scope, path: discovery.path, sourceRequirement: requirements.requirement), beforeApply: { - Terminal.instructionTargets( - $0.targets.filter(\.foreign), paths: location.paths) + Terminal.instructionNotes($0) + Terminal.instructionTargets($0, paths: location.paths, foreignOnly: true) }) } - if outcome.result == nil { + guard let result = outcome.result else { Terminal.availableInstructions(outcome.available) Terminal.write("Select names with 'agents instructions add '.\n") - } else if let result = outcome.result { - let selected = - names.isEmpty - ? outcome.available - : names.compactMap { name in outcome.available.first { $0.record.name == name } } - let locked = try InstructionOperations.listManaged(scope: location.scope) - for target in result.targets - where !target.afterAgents.isEmpty && locked.targets[target.target]?.import == nil { - // A project section goes only to the target in the directory its paths share. - let directory = (target.target as NSString).deletingLastPathComponent - let added = selected.filter { - location.scope == .user || $0.section.directory == directory - }.map { Terminal.line($0.record.name) } - if added.isEmpty { continue } + return + } + let paths = location.paths + let roots = location.scope == .user ? [] : [paths.environment.projectDirectory] + let mapping = InstructionOperations.export(projectRoots: roots, environment: paths.environment) + .first { $0.scope == location.scope } + let selected = names.isEmpty ? outcome.available.map(\.record.name) : names + for target in result.targets where target.changed { + let assignment = mapping?.targets.first { $0.target == target.target } + let added = selected.filter { name in + assignment?.sections.contains { $0.name == name && $0.source == outcome.sourceID } == true + } + if added.isEmpty { + Terminal.instructionCompletion(target, paths: paths) + } else { Terminal.write( - "Added \(added.joined(separator: ", ")) to \(location.paths.path(target.url.path)) (\(Terminal.recipients(target.afterAgents))).\n" + "Added \(added.map(Terminal.line).joined(separator: ", ")) to \(paths.path(target.url.path)) (\(Terminal.recipients(target.afterAgents))).\n" ) } } @@ -106,20 +112,16 @@ struct ListInstructions: ParsableCommand { func run() throws { if let source { - let outcome = try withRecovery { - try InstructionOperations.add( - InstructionAddOptions( - source: source, listOnly: true, scope: location.scope, path: discovery.path)) - } + let outcome = try InstructionOperations.add( + InstructionAddOptions( + source: source, listOnly: true, scope: location.scope, path: discovery.path)) if json { try Terminal.json(InstructionSourceReport(scope: location.scope.rawValue, outcome: outcome)) } else { Terminal.availableInstructions(outcome.available) } } else { - let locked = try withRecovery { - try InstructionOperations.listManaged(scope: location.scope) - } + let locked = try InstructionOperations.listManaged(scope: location.scope) let report = InstructionListReport(scope: location.scope.rawValue, locked: locked) if json { try Terminal.json(report) @@ -130,9 +132,10 @@ struct ListInstructions: ParsableCommand { } } -struct RemoveInstructions: ParsableCommand { +struct RemoveInstructions: AsyncParsableCommand { static let configuration = CommandConfiguration( - commandName: "remove", abstract: "Remove declared sections from instruction files and prompts.") + commandName: "remove", abstract: "Remove declared sections from instruction files and prompts.", + discussion: "Use --agent to set the recipient list for remaining sections in this scope.") @Argument(help: "Section names, or source-alias:name when a name is ambiguous.") var names: [String] @@ -143,24 +146,28 @@ struct RemoveInstructions: ParsableCommand { if names.isEmpty { throw ValidationError("Specify at least one instruction section name") } } - func run() throws { - let result = try withRecovery { - try InstructionOperations.remove( - names: names, scope: location.scope, agents: agents.recipients, - beforeApply: { Terminal.instructionTargets($0.targets, paths: location.paths) }) + func run() async throws { + let request = UpdateRequest( + operation: .remove, kinds: [.instructions], names: names, agents: agents.recipients) + let review = try previewAfterRecovery(scope: location.scope) { + try UpdateOperations.previewLifecycle(request, intent: .uninstall, scope: location.scope) } - for target in result.targets where target.changed { - Terminal.write( - "Removed \(names.map(Terminal.line).joined(separator: ", ")) from \(location.paths.path(target.url.path)).\n" - ) + if review.ownershipConflict == nil { + Terminal.instructionNotes(review.report.instructions) + Terminal.instructionTargets(review.report.instructions, paths: location.paths) + } + try await applyLifecycle(review, scope: location.scope) { receipt, _ in + let result = receipt.report.instructions + Terminal.updatedInstructions(result, paths: location.paths) + Terminal.promptReminder(result.changedPrompts) } - Terminal.promptReminder(result.changedPrompts) } } -struct UpdateInstructions: ParsableCommand { +struct UpdateInstructions: AsyncParsableCommand { static let configuration = CommandConfiguration( - commandName: "update", abstract: "Preview or apply updates to all declared instructions.") + commandName: "update", abstract: "Preview or apply updates to all declared instructions.", + discussion: "Use --agent to set the recipient list for all sections in this scope.") @OptionGroup var options: UpdateOptions @OptionGroup var agents: InstructionAgentOptions @@ -171,14 +178,30 @@ struct UpdateInstructions: ParsableCommand { if replace && !options.apply { throw ValidationError("--replace requires --apply") } } - func run() throws { - let result = try options.updateInstructions(agents: agents.recipients, replace: replace) + func run() async throws { + let scope = options.location.scope + let paths = options.location.paths + if options.apply { + let review = try previewAfterRecovery(scope: scope) { + try InstructionOperations.previewCompilation( + scope: scope, agents: agents.recipients, replace: replace) + } + if review.ownershipConflict == nil { + Terminal.instructionDifferences(review.report.instructions, paths: paths) + } + try await applyLifecycle(review, scope: scope) { receipt, _ in + Terminal.updatedInstructions(receipt.report.instructions, paths: paths) + } + return + } + + let result = try InstructionOperations.updateInstalled(scope: scope, agents: agents.recipients) if options.json { try Terminal.json( - InstructionPreviewReport( - scope: options.location.scope.rawValue, instructions: InstructionChanges(result))) + InstructionPreviewReport(scope: scope.rawValue, instructions: InstructionChanges(result))) } else { - options.finishInstructions(result) + Terminal.instructionDifferences(result, paths: paths) + options.previewNotice(changed: result.hasChanges && result.conflicts.isEmpty) } } } @@ -198,22 +221,11 @@ struct RenderChatGPT: ParsableCommand { @OptionGroup var location: ScopeOptions func run() throws { - let bytes = try withRecovery { - _ = try InstructionOperations.listManaged(scope: location.scope) - let declarationURL = StateStore(scope: location.scope, environment: RuntimeEnvironment()) - .declarationURL - let declaration: Declaration - do { - declaration = try JSONDecoder().decode( - Declaration.self, from: Data(contentsOf: declarationURL)) - } catch CocoaError.fileReadNoSuchFile { - declaration = Declaration() - } - guard declaration.instructions?.chatgpt?[prompt] != nil else { - throw HumanOutputError.undeclaredPrompt(prompt) - } - return try InstructionOperations.renderChatGPT(prompt: prompt, scope: location.scope) + let declaration = try StateStore(scope: location.scope).loadDeclaration() + guard try declaration.instructions?.chatgpt?[prompt] != nil else { + throw HumanOutputError.undeclaredPrompt(prompt) } + let bytes = try InstructionOperations.renderChatGPT(prompt: prompt, scope: location.scope) Terminal.write(Terminal.text(String(decoding: bytes, as: UTF8.self))) } } diff --git a/Sources/CLI/InstructionReports.swift b/Sources/CLI/InstructionReports.swift index fd03067..b8f9529 100644 --- a/Sources/CLI/InstructionReports.swift +++ b/Sources/CLI/InstructionReports.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsSkills +import AgentsUpdates struct SectionItem: Encodable { let name: String @@ -117,12 +118,16 @@ struct InstructionChanges: Encodable { let sections: [SectionChange] let targets: [InstructionTargetChangeItem] let changedPrompts: [String] + let advisories: [String]? + let conflicts: [String]? init(_ report: InstructionUpdateReport) { lockMissing = report.lockMissing sections = report.sections.map(SectionChange.init) targets = report.targets.map(InstructionTargetChangeItem.init) changedPrompts = report.changedPrompts + advisories = report.advisories.isEmpty ? nil : report.advisories + conflicts = report.conflicts.isEmpty ? nil : report.conflicts changed = report.hasChanges } } @@ -246,11 +251,15 @@ struct InstallReport: Encodable { let scope: String let skills: [RestoredSkill] let instructions: InstructionChanges - - init(scope: String, skills: [InstallResult], instructions: InstructionChanges) { - self.scope = scope - self.skills = skills.map(RestoredSkill.init) - self.instructions = instructions + let components: [ComponentChangeItem] + let lifecycle: PackageLifecycleReport? + + init(_ result: UpdateApplyResult, lifecycle: PackageLifecycleReport?) { + self.lifecycle = lifecycle + scope = result.report.scope.rawValue + skills = result.installedSkills.map(RestoredSkill.init) + instructions = InstructionChanges(result.report.instructions) + components = result.report.components.map(ComponentChangeItem.init) } } diff --git a/Sources/CLI/JSONReports.swift b/Sources/CLI/JSONReports.swift index 7a63162..f7755fc 100644 --- a/Sources/CLI/JSONReports.swift +++ b/Sources/CLI/JSONReports.swift @@ -74,14 +74,18 @@ struct UpdateReport: Encodable { let skills: [UpdateItem] let instructions: InstructionChanges? + let marketplaceChanges: [PackagePinChange]? let lockMissing: Bool? + let components: [ComponentChangeItem]? init(scope: String, results: [UpdateResult]) { self.scope = scope changed = results.contains(where: \.changed) skills = results.map(UpdateItem.init) instructions = nil + marketplaceChanges = nil lockMissing = nil + components = nil } init(_ report: CombinedUpdateReport) { @@ -89,7 +93,36 @@ struct UpdateReport: Encodable { changed = report.hasChanges skills = report.skills.map(UpdateItem.init) instructions = InstructionChanges(report.instructions) + marketplaceChanges = report.marketplaceChanges?.compactMap(PackagePinChange.init) lockMissing = report.lockMissing + components = report.components.map(ComponentChangeItem.init) + } +} + +struct PackagePinChange: Encodable { + struct Release: Encodable { + let package: String + let version: String + let archiveDigest: String + let catalogCommit: String? + + init(_ pin: MarketplacePin) { + package = pin.dependency.coordinate.package + version = pin.dependency.coordinate.version + archiveDigest = pin.archiveDigest + catalogCommit = pin.catalogCommit + } + } + + let name: String + let before: Release? + let after: Release? + + init?(_ change: MarketplacePackageUpdate) { + guard let pin = change.after ?? change.before else { return nil } + name = pin.dependency.name + before = change.before.map(Release.init) + after = change.after.map(Release.init) } } @@ -230,13 +263,16 @@ struct DoctorRoot: Encodable { init( root: String, scope: String, report: DoctorReport, instructions: InstructionDoctorReport, - environment: RuntimeEnvironment + environment: RuntimeEnvironment, inventory: ScopeInspection? = nil, + policyChecks: [CheckItem] = [], ci: Bool = false ) { self.root = root self.scope = scope checks = - report.checks.map { CheckItem($0, environment: environment) } - + instructions.diagnostics.map { CheckItem($0, environment: environment) } + report.checks.map { CheckItem($0, environment: environment, ci: ci) } + + instructions.diagnostics.map { CheckItem($0, environment: environment, ci: ci) } + + (inventory.map { CheckItem.inventory($0, environment: environment) } ?? []) + + policyChecks ok = !checks.contains { $0.status == "error" } } } @@ -248,23 +284,28 @@ struct CheckItem: Encodable { let message: String let path: String? - init(_ check: DoctorCheck, environment: RuntimeEnvironment) { + init(_ check: DoctorCheck, environment: RuntimeEnvironment, ci: Bool = false) { kind = "skills" id = check.id - status = check.id == "pending-recovery" ? "error" : check.status.rawValue + status = + (["pending-recovery", "unresolved-transaction"].contains(check.id) + || (ci && ["missing", "copy-drift", "broken-link"].contains(check.id))) + ? "error" : check.status.rawValue message = check.id == "pending-recovery" ? Self.pendingRecoveryMessage(path: check.path, environment: environment) : check.message path = check.path } - init(_ diagnostic: InstructionDiagnostic, environment: RuntimeEnvironment) { + init(_ diagnostic: InstructionDiagnostic, environment: RuntimeEnvironment, ci: Bool = false) { kind = "instructions" id = diagnostic.kind.rawValue switch diagnostic.kind { case .invalidTarget, .foreignTarget, .invalidLink, .invalidConfiguration, .stateUnavailable, - .pendingRecovery: + .pendingRecovery, .unresolvedTransaction: status = "error" + case .drift, .missingTarget, .missingLock, .ownChanged: + status = ci ? "error" : "warning" default: status = "warning" } @@ -275,6 +316,78 @@ struct CheckItem: Encodable { path = diagnostic.path?.path } + init(_ violation: SourcePolicyViolation) { + kind = "sourcePolicy" + id = violation.reason.rawValue + status = "error" + let reference = violation.reference.map { " (" + $0 + ")" } ?? "" + message = + "\(violation.scope.rawValue) policy: \(violation.reason.rawValue) \(violation.origin)\(reference)" + path = violation.policyURL.path + } + + init(_ finding: OrganizationPolicyFinding) { + self.init( + kind: "organizationPolicy", id: finding.rule, + status: finding.outcome == .block ? "error" : "warning", + message: finding.identity + " — " + finding.message, + path: finding.document.map { $0.isFileURL ? $0.path : $0.absoluteString }) + } + + init(kind: String, id: String, status: String, message: String, path: String?) { + self.kind = kind + self.id = id + self.status = status + self.message = message + self.path = path + } + + static func inventory(_ inspection: ScopeInspection, environment: RuntimeEnvironment) + -> [CheckItem] + { + if inspection.recovery.pending { + return [ + .init( + kind: "components", + id: inspection.recovery.requiresOwner ? "unresolved-transaction" : "pending-recovery", + status: "error", + message: inspection.recovery.requiresOwner + ? (inspection.recovery.diagnostic ?? "Transaction recovery requires owner action") + : pendingRecoveryMessage( + path: StateStore(scope: inspection.scope, environment: environment).directory.path, + environment: environment), + path: StateStore(scope: inspection.scope, environment: environment).directory.path) + ] + } + let owners = Set( + inspection.components.filter { $0.kind != .skills && $0.kind != .instructions }.map(\.record)) + let packageChecks: [CheckItem] = + inspection.marketplaceIssue.map { + [ + .init( + kind: "marketplace", id: "package-lock", status: "error", message: $0.description, + path: StateStore(scope: inspection.scope, environment: environment).declarationURL.path) + ] + } ?? [] + let pendingChecks: [CheckItem] = + inspection.pendingMarketplaceDeployment.map { pending in + [ + .init( + kind: "marketplace", id: "pending-deployment", status: "error", + message: "Package lock " + pending.digest + + " awaits deployment. Review it with 'agents marketplace deploy'.", + path: nil) + ] + } ?? [] + return packageChecks + pendingChecks + + inspection.deployments.filter { !owners.isDisjoint(with: $0.ownerRecords) }.map { + .init( + kind: "components", id: $0.format, status: $0.status == .current ? "ok" : "error", + message: $0.diagnostic ?? "Managed deployment is \($0.status.rawValue)", + path: $0.location.path) + } + } + private static func pendingRecoveryMessage(path: String?, environment: RuntimeEnvironment) -> String { diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index 7c9a90c..44d7b18 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -5,41 +5,47 @@ import AgentsUpdates import ArgumentParser import Foundation -struct Install: ParsableCommand { +struct Install: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "install", - abstract: "Restore skills and instructions using exact pins and recipients from the lock.") + abstract: "Restore all components using exact pins and recipients from the lock.") @OptionGroup var location: ScopeOptions + @OptionGroup var bindings: BindingOptions @Flag(help: "Print the versioned JSON report.") var json = false - func run() throws { - let report = try withRecovery { - try SkillOperations.installResolvedReport(scope: location.scope) + func run() async throws { + let review = try previewAfterRecovery(scope: location.scope) { + try UpdateOperations.previewLifecycle( + UpdateRequest(operation: .restore), intent: .install, scope: location.scope) } - if !json { - if report.installed.isEmpty { + try await applyLifecycle( + review, scope: location.scope, bindingProvider: bindings.provider(), json: json, + completed: finish) + } + + private func finish(_ result: UpdateApplyResult, _ lifecycle: PackageLifecycleReport?) throws { + if json { + try Terminal.json(InstallReport(result, lifecycle: lifecycle)) + } else { + Terminal.instructionNotes(result.report.instructions) + if result.installedSkills.isEmpty { Terminal.write("No locked skills to restore.\n") } else { - Terminal.installed(report.installed) + Terminal.installed(result.installedSkills) } - } - let instructions = try withRecovery { - try InstructionOperations.installResolvedReport(scope: location.scope) - } - if json { - try Terminal.json( - InstallReport( - scope: location.scope.rawValue, skills: report.installed, - instructions: InstructionChanges(instructions))) - return - } - if instructions.targets.isEmpty { - Terminal.write("No locked instruction targets to restore.\n") - } else { - for target in instructions.targets { - Terminal.write("Restored instructions in \(location.paths.path(target.url.path)).\n") + if result.report.instructions.targets.isEmpty { + Terminal.write("No locked instruction targets to restore.\n") + } else { + for target in result.report.instructions.targets where target.changed { + if target.after == nil { + Terminal.instructionCompletion(target, paths: location.paths) + } else { + Terminal.write("Restored instructions in \(location.paths.path(target.url.path)).\n") + } + } } + Terminal.componentChanges(result.report.components, paths: location.paths, applied: true) } } } @@ -53,45 +59,6 @@ struct UpdateOptions: ParsableArguments { if json && apply { throw ValidationError("--json is for previews; remove --apply or --json") } } - func updateSkills(names: [String] = []) throws -> [UpdateResult] { - try withRecovery { - try SkillOperations.updateInstalled( - scope: location.scope, skillNames: names, apply: apply, - beforeApply: { results in - Terminal.differences(results, paths: location.paths) - }) - } - } - - func finishSkills(_ results: [UpdateResult]) { - if apply { - Terminal.updatedSkills(results) - } else { - Terminal.differences(results, paths: location.paths) - } - } - - func updateInstructions(agents: [AgentID]? = nil, replace: Bool = false) throws - -> InstructionUpdateReport - { - try withRecovery { - try InstructionOperations.updateInstalled( - scope: location.scope, agents: agents, apply: apply, replace: replace, - beforeApply: { result in - Terminal.instructionDifferences(result, paths: location.paths) - }) - } - } - - func finishInstructions(_ result: InstructionUpdateReport) { - if apply { - Terminal.updatedInstructions(result, paths: location.paths) - } else { - Terminal.instructionDifferences(result, paths: location.paths) - previewNotice(changed: result.hasChanges) - } - } - func previewNotice(changed: Bool) { if !apply && changed { Terminal.write("Preview only. Run again with --apply to write these changes.\n") @@ -99,49 +66,69 @@ struct UpdateOptions: ParsableArguments { } } -struct Update: ParsableCommand { +struct Update: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "update", - abstract: "Preview or apply updates to all declared skills and instructions.") + abstract: "Preview or apply updates to all declared components.") @OptionGroup var options: UpdateOptions + @OptionGroup var writing: ComponentWriteOptions - func run() throws { + func run() async throws { + let scope = options.location.scope let paths = options.location.paths if options.apply { - let receipt = try withRecovery { - try UpdateOperations.withPreparedUpdate(scope: options.location.scope) { update in - Terminal.updateDifferences(update.report, paths: paths) - return try update.apply() - } + let review = try previewAfterRecovery(scope: scope) { + try UpdateOperations.previewLifecycle(writing.request(), intent: .update, scope: scope) + } + if review.ownershipConflict == nil { + Terminal.updateDifferences(review.report, paths: paths) + } + try await applyLifecycle(review, scope: scope, bindingProvider: writing.bindings.provider()) { + receipt, _ in + Terminal.updatedSkills(receipt.report.skills) + Terminal.updatedInstructions(receipt.report.instructions, paths: paths) + Terminal.componentChanges(receipt.report.components, paths: paths, applied: true) + Terminal.promptReminder(receipt.report.instructions.changedPrompts) } - Terminal.updatedSkills(receipt.report.skills) - Terminal.updatedInstructions(receipt.report.instructions, paths: paths) - Terminal.promptReminder(receipt.report.instructions.changedPrompts) } else { - let report = try UpdateOperations.preview(scope: options.location.scope) + let report = try UpdateOperations.preview(writing.request(), scope: options.location.scope) if options.json { try Terminal.json(UpdateReport(report)) } else { Terminal.updateDifferences(report, paths: paths) - options.previewNotice(changed: report.hasChanges) + options.previewNotice(changed: report.hasChanges && report.instructions.conflicts.isEmpty) } } } } -struct UpdateSkills: ParsableCommand { +struct UpdateSkills: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "update", abstract: "Preview or apply updates to selected or all declared skills.") @Argument(help: "Limit the update to these skill names.") var names: [String] = [] @OptionGroup var options: UpdateOptions - func run() throws { - let skills = try options.updateSkills(names: names) + func run() async throws { + let scope = options.location.scope + if options.apply { + let review = try previewAfterRecovery(scope: scope) { + try UpdateOperations.previewLifecycle( + UpdateRequest(kinds: [.skills], names: names), intent: .update, scope: scope) + } + if review.ownershipConflict == nil { + Terminal.differences(review.report.skills, paths: options.location.paths) + } + try await applyLifecycle(review, scope: scope) { receipt, _ in + Terminal.updatedSkills(receipt.report.skills) + } + return + } + + let skills = try SkillOperations.updateInstalled(scope: scope, skillNames: names) if options.json { - try Terminal.json( - UpdateReport(scope: options.location.scope.rawValue, results: skills)) + try Terminal.json(UpdateReport(scope: scope.rawValue, results: skills)) } else { - options.finishSkills(skills) + Terminal.differences(skills, paths: options.location.paths) options.previewNotice(changed: skills.contains(where: \.changed)) } } @@ -150,7 +137,7 @@ struct UpdateSkills: ParsableCommand { struct Doctor: ParsableCommand { static let configuration = CommandConfiguration( commandName: "doctor", - abstract: "Compare skills and instructions with the lock and report problems.", + 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." ) @@ -160,6 +147,10 @@ struct Doctor: ParsableCommand { name: .long, parsing: .upToNextOption, help: "Audit these project directories read-only. Repeat for several.") var root: [String] = [] + @Flag(help: "Fail CI when locked skill or instruction outputs are missing or changed.") var ci = + false + @Flag(help: "Require a readable organization source policy in the audit.") + var requireOrganizationPolicy = false @Flag(help: "Print the versioned JSON report.") var json = false func validate() throws { @@ -189,11 +180,59 @@ struct Doctor: ParsableCommand { environment: runtime) let instructions = try InstructionOperations.doctor( scope: location.scope, environment: runtime) + let inventory = try UpdateOperations.inspect(scope: location.scope, environment: runtime) + let policyChecks: [CheckItem] + if inventory.recovery.pending { + policyChecks = [] + } else { + do { + let hasSelection = + runtime.userOrganizationPolicy != nil + || (location.scope == .project && runtime.projectOrganizationPolicy != nil) + var checks: [CheckItem] + var loadedGovernance = false + if hasSelection { + let audit = try OrganizationPolicyOperations.audit( + scope: location.scope, environment: runtime) + loadedGovernance = audit.organization.policies.contains { $0.outcome == .loaded } + var findings = audit.organization.findings + for finding in audit.pendingMarketplacePolicy?.findings ?? [] + where !findings.contains(finding) { + findings.append(finding) + } + checks = + audit.sourceViolations.map(CheckItem.init) + + findings.map(CheckItem.init) + } else { + let audit = try SourcePolicyOperations.audit( + scope: location.scope, environment: runtime) + checks = audit.violations.map(CheckItem.init) + } + if requireOrganizationPolicy && !loadedGovernance { + let layers = try SourcePolicyOperations.inspect( + scope: location.scope, environment: runtime + ).effective.layers + if !layers.contains(where: { $0.scope == .organization }) { + checks.append( + CheckItem( + kind: "sourcePolicy", id: "missingOrganizationPolicy", + status: "error", message: "Select a readable organization policy.", path: nil)) + } + } + policyChecks = checks + } catch { + policyChecks = [ + CheckItem( + kind: "sourcePolicy", id: "auditUnavailable", status: "error", + message: String(describing: error), path: nil) + ] + } + } reports.append( DoctorRoot( root: location.scope == .user ? environment.homeDirectory.path : project.path, scope: location.scope.rawValue, report: report, instructions: instructions, - environment: runtime)) + environment: runtime, inventory: inventory, policyChecks: policyChecks, ci: ci)) } let report = DoctorOutput(roots: reports) if json { diff --git a/Sources/CLI/LineDiff.swift b/Sources/CLI/LineDiff.swift index 4c3f1c6..72ba2f7 100644 --- a/Sources/CLI/LineDiff.swift +++ b/Sources/CLI/LineDiff.swift @@ -87,7 +87,7 @@ enum LineDiff { private static func lines(_ data: Data) -> [Line]? { guard let text = String(data: data, encoding: .utf8) else { return nil } if text.isEmpty { return [] } - var parts = text.components(separatedBy: "\n") + var parts = Terminal.splitLines(text) let terminated = data.last == 10 if terminated { parts.removeLast() } return parts.enumerated().map { diff --git a/Sources/CLI/MCPCommand.swift b/Sources/CLI/MCPCommand.swift new file mode 100644 index 0000000..9f88b7b --- /dev/null +++ b/Sources/CLI/MCPCommand.swift @@ -0,0 +1,84 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct MCPCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "mcp", + abstract: "Discover, configure and test MCP servers.", + subcommands: [SearchMCP.self, ShowMCP.self, AddRegistryMCP.self, TestMCP.self]) +} + +struct TestMCP: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "test", + abstract: + "Initialize one exact managed MCP server and discover tools; may start its process or contact its endpoint." + ) + @OptionGroup var selection: ComponentSelector + @OptionGroup var location: ScopeOptions + @OptionGroup var bindings: BindingOptions + @Flag(help: "Print the versioned JSON result.") var json = false + + mutating func run() async throws { + let environment = RuntimeEnvironment() + let inspection = try UpdateOperations.inspect(scope: location.scope, environment: environment) + let selected = try selection.select(in: inspection) + guard + inspection.components.contains(where: { + $0.selection.identity == selected.identity && $0.kind == .mcpServer + }) + else { + throw CoreError.invalidState("select an MCP server component") + } + let snapshot = try MCPConnectionOperations.snapshot( + selection: selected, scope: location.scope, environment: environment) + let provider = try bindings.provider() + for name in MCPConnectionOperations.describe(snapshot).requiredBindings + where provider.variables[name] == nil { + throw CoreError.invalidState("runtime binding unavailable: \(name)") + } + let result = await MCPConnectionOperations.test( + snapshot, environment: environment, bindings: provider) + let report = MCPTestReport(result) + if json { + try Terminal.json(report) + } else { + Terminal.write( + "MCP \(Terminal.line(selection.name)): \(Terminal.line(report.outcome))\(report.issue.map { " (\(Terminal.line($0)))" } ?? "").\n" + ) + for tool in report.tools { Terminal.write(" \(Terminal.line(tool.name))\n") } + } + guard result.outcome == .discovered || result.outcome == .noTools, result.cleanupComplete else { + throw ExitCode.failure + } + } +} + +struct MCPTestReport: Encodable { + let schemaVersion = 1 + let kind = "mcp-test" + let transport: String + let outcome: String + let issue: String? + let negotiatedVersion: String? + let cleanupComplete: Bool + let elapsed: TimeInterval + let tools: [Tool] + struct Tool: Encodable { + let name: String + let title: String? + let description: String? + } + + init(_ result: MCPConnectionTestResult) { + transport = result.transport.rawValue + outcome = result.outcome.rawValue + issue = result.issue?.rawValue + negotiatedVersion = result.negotiatedVersion + cleanupComplete = result.cleanupComplete + elapsed = result.elapsed + tools = result.tools.map { .init(name: $0.name, title: $0.title, description: $0.description) } + } +} diff --git a/Sources/CLI/MCPRegistryCommands.swift b/Sources/CLI/MCPRegistryCommands.swift new file mode 100644 index 0000000..5b8a1c7 --- /dev/null +++ b/Sources/CLI/MCPRegistryCommands.swift @@ -0,0 +1,215 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct RegistryOptions: ParsableArguments { + @Option( + help: "MCP Registry v0.1 base URL. Uses MCP_REGISTRY_URL or the public registry when omitted.") + var registry: String? + @Option(help: "Environment variable containing a bearer token for this registry request.") + var tokenEnv: String? + + func client() throws -> MCPRegistry { + guard let registry else { return try .configured() } + guard let url = URL(string: registry) else { throw ValidationError("Invalid registry URL") } + return try MCPRegistry(endpoint: url) + } + + func credentials() throws -> [String: String] { + guard let tokenEnv else { return [:] } + guard let token = ProcessInfo.processInfo.environment[tokenEnv], !token.isEmpty else { + throw ValidationError("The registry token environment variable is empty or unavailable") + } + return ["Authorization": "Bearer " + token] + } +} + +struct SearchMCP: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "search", abstract: "Search an MCP registry.") + @Argument(help: "Text to search for. Omit to browse.") var query: String? + @OptionGroup var connection: RegistryOptions + @OptionGroup var location: ScopeOptions + @Option(help: "Number of results per page (1–100).") var limit = 20 + @Option(help: "Continue from a previous page.") var cursor: String? + @Flag(help: "Include older versions.") var allVersions = false + @Flag(help: "Print the JSON result.") var json = false + + mutating func run() async throws { + let page = try await connection.client().search( + query, version: allVersions ? nil : "latest", limit: limit, cursor: cursor, + credentials: connection.credentials(), scope: location.scope) + if json { + try Terminal.json( + RegistryPageReport( + servers: page.servers.map(RegistryServerReport.init), nextCursor: page.nextCursor)) + return + } + for server in page.servers { + Terminal.write( + "\(Terminal.line(server.name)) \(Terminal.line(server.version)) \(Terminal.line(server.description))\n" + ) + } + if page.servers.isEmpty { Terminal.write("No matching servers.\n") } + if let cursor = page.nextCursor { Terminal.write("Next cursor: \(Terminal.line(cursor))\n") } + } +} + +struct RegistryServerOptions: ParsableArguments { + @Argument(help: "Full server name in the registry.") var server: String + @Option(help: "Published server version, or latest.") var serverVersion = "latest" + @OptionGroup var connection: RegistryOptions + + func load(in scope: InstallScope) async throws -> MCPRegistryServer { + try await connection.client().server( + named: server, version: serverVersion, credentials: connection.credentials(), scope: scope) + } +} + +struct ShowMCP: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "show", abstract: "Inspect a registry server and its installation choices.") + @OptionGroup var selection: RegistryServerOptions + @OptionGroup var location: ScopeOptions + @Flag(help: "Print the JSON result.") var json = false + + mutating func run() async throws { + let report = try await RegistryServerReport(selection.load(in: location.scope)) + if json { + try Terminal.json(report) + return + } + Terminal.write( + "\(Terminal.line(report.name)) \(Terminal.line(report.version))\n\(Terminal.line(report.description))\n" + ) + for choice in report.choices { + Terminal.write( + " \(choice.number). \(Terminal.line(choice.transport)) \(Terminal.line(choice.source))\n") + for binding in choice.inputs { + Terminal.write( + " \(Terminal.line(binding.name)) (\(binding.required ? "required" : "optional"))\n") + } + for input in choice.inputs where !input.choices.isEmpty { + Terminal.write( + " \(Terminal.line(input.name)) choices: \(Terminal.line(input.choices.joined(separator: ", ")))\n" + ) + } + if choice.requiresPackageCommand { Terminal.write(" Supply --package-command.\n") } + if let reason = choice.unavailable { Terminal.write(" \(Terminal.line(reason))\n") } + } + } +} + +struct RegistryPageReport: Encodable { + let schemaVersion = 1 + let servers: [RegistryServerReport] + let nextCursor: String? +} + +struct RegistryServerReport: Encodable { + let schemaVersion = 1 + let name: String + let version: String + let description: String + let choices: [Choice] + + struct Input: Encodable { + let name: String + let required: Bool + let secret: Bool + let choices: [String] + } + + struct Choice: Encodable { + let number: Int + let transport: String + let source: String + let inputs: [Input] + let requiresPackageCommand: Bool + let unavailable: String? + } + + init(_ server: MCPRegistryServer) { + name = server.name + version = server.version + description = server.description + choices = server.choices.enumerated().map { index, choice in + let source: String + switch choice.source { + case .remote(let endpoint): source = endpoint?.absoluteString ?? "remote" + case .package(let package): source = "\(package.registryType):\(package.identifier)" + } + return Choice( + number: index + 1, transport: choice.transport, source: source, + inputs: choice.bindings.map { + Input(name: $0.name, required: $0.isRequired, secret: $0.isSecret, choices: $0.choices) + }, + requiresPackageCommand: choice.requiresPackageCommand, unavailable: choice.unavailableReason + ) + } + } +} + +struct AddRegistryMCP: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "add", + abstract: "Preview a registry MCP installation, or apply it to selected clients.") + @OptionGroup var selection: RegistryServerOptions + @OptionGroup var options: UpdateOptions + @OptionGroup var writing: ComponentWriteOptions + @Option(help: "Managed name to write in the selected clients.") var name: String + @Option(help: "Client to configure. Repeat for multiple clients.", transform: AgentID.parse) + var agent: [AgentID] + @Option(help: "Installation choice number from mcp show (starting at 1).") var choice: Int? + @Option(help: "Set INPUT=ENV_VAR, or INPUT=VALUE for a listed choice.") + var input: [String] = [] + @Option(help: "Console command provided by the selected package.") var packageCommand: String? + + mutating func run() async throws { + let server = try await selection.load(in: options.location.scope) + let number = choice ?? (server.choices.count == 1 ? 1 : 0) + guard number > 0, number <= server.choices.count else { + throw ValidationError("Select a valid --choice from mcp show") + } + let references = try BindingOptions.mappings(input, option: "--input") + let scope = options.location.scope + let inspection = try UpdateOperations.inspect(scope: scope) + try requireCommittedInspection(inspection) + let selected = server.choices[number - 1] + var bindings: [String: MCPRegistryBinding] = [:] + for (key, value) in references { + if let requirement = selected.bindings.first(where: { $0.name == key }), + !requirement.choices.isEmpty + { + bindings[key] = .choice(value) + } else { + bindings[key] = .environment(value) + } + } + let addition = try selected.select( + named: name, agents: agent, in: inspection, bindings: bindings, packageCommand: packageCommand + ) + let request = writing.request(addition.updateRequest()) + if options.apply { + let receipt = try withRecovery { + try UpdateOperations.withPreparedUpdate( + request, scope: scope, bindingProvider: writing.bindings.provider() + ) { update in + Terminal.updateDifferences(update.report, paths: options.location.paths) + return try update.apply() + } + } + Terminal.componentChanges( + receipt.report.components, paths: options.location.paths, applied: true) + } else { + let report = try UpdateOperations.preview(request, scope: scope) + if options.json { + try Terminal.json(UpdateReport(report)) + } else { + Terminal.updateDifferences(report, paths: options.location.paths) + options.previewNotice(changed: report.hasChanges && report.instructions.conflicts.isEmpty) + } + } + } +} diff --git a/Sources/CLI/ManifestCommands.swift b/Sources/CLI/ManifestCommands.swift new file mode 100644 index 0000000..a179dae --- /dev/null +++ b/Sources/CLI/ManifestCommands.swift @@ -0,0 +1,32 @@ +import AgentsCore +import AgentsManifest +import ArgumentParser +import Foundation + +struct Manifest: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "manifest", abstract: "Inspect local declarations.", + subcommands: [DumpManifest.self]) +} + +struct DumpManifest: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "dump", abstract: "Print the local manifest's JSON and source locations." + ) + + @OptionGroup var location: ScopeOptions + @Flag(help: "Print the manifest JSON contract.") var json = false + + func validate() throws { + if !json { throw ValidationError("manifest dump requires --json") } + } + + func run() throws { + let store = StateStore(scope: location.scope) + guard let document = try store.loadManifest() else { + throw CoreError.notFound("declaration at \(store.declarationURL.path)") + } + let bytes = try ManifestDump(document: document).encodedJSON() + FileHandle.standardOutput.write(Data(bytes)) + } +} diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift new file mode 100644 index 0000000..1213e0e --- /dev/null +++ b/Sources/CLI/MarketplaceCommands.swift @@ -0,0 +1,531 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct MarketplaceCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "marketplace", abstract: "Browse team packages and manage their releases.", + subcommands: [ + RegisterMarketplace.self, ListMarketplaces.self, UnregisterMarketplace.self, + SearchMarketplace.self, VerifyMarketplace.self, PublishPackage.self, + StageHostedMarketplace.self, + InstallMarketPackage.self, + InstalledPackages.self, OutdatedPackages.self, UpgradeMarketPackage.self, + RemoveMarketPackage.self, ResolveMarketPackages.self, MarketplaceDependencies.self, + MarketplaceWhy.self, ResolvePendingMarketPackages.self, DeployLockedMarketPackages.self, + ]) +} + +struct CatalogOptions: ParsableArguments { + @Option(help: "Existing team marketplace directory.") var directory: String? + @Option(help: "Hosted marketplace HTTPS index URL.") var index: String? + @Option(help: "Git marketplace repository.") var git: String? + @Option(help: "Git ref to browse.") var ref: String? + @Option(help: "Marketplace directory within the Git repository.") var subpath: String? + + @Option(help: "Registered marketplace name.") var catalog: String? + + func directOrigin(anchorDirectory: Bool = false) throws -> MarketplaceOrigin { + guard catalog == nil else { + throw ValidationError("Choose a directory, Git repository or hosted index to register") + } + let origin: MarketplaceOrigin + switch (directory, git, index) { + case (let path?, nil, nil) where ref == nil && subpath == nil: + origin = try MarketplaceOrigin( + kind: .directory, + location: anchorDirectory ? URL(fileURLWithPath: path).standardizedFileURL.path : path) + case (nil, let repository?, nil): + origin = try MarketplaceOrigin(kind: .git, location: repository, ref: ref, subpath: subpath) + case (nil, nil, let address?) where ref == nil && subpath == nil: + guard let url = URL(string: address) else { throw ValidationError("Invalid index URL") } + origin = try MarketplaceOrigin(hostedIndex: url) + default: + throw ValidationError( + "Choose one of --directory, --git and --index. --ref and --subpath require --git.") + } + return origin + } + + func registration(in scope: InstallScope) throws -> MarketplaceRegistration { + if let catalog { + guard directory == nil, git == nil, index == nil, ref == nil, subpath == nil else { + throw ValidationError("--catalog cannot be combined with an explicit marketplace address") + } + return try MarketplaceDirectory.lookup(catalog, scope: scope) + } + return try MarketplaceRegistration(name: "catalog", origin: directOrigin(anchorDirectory: true)) + } + + var specified: Bool { + catalog != nil || directory != nil || git != nil || index != nil || ref != nil || subpath != nil + } + +} + +struct HostedAccessOptions: ParsableArguments { + @Option( + help: + "Bind a user-registered catalog to a bearer-token environment variable as NAME=VARIABLE. Repeat for multiple catalogs." + ) + var tokenEnv: [String] = [] + @Option(help: "Trusted HTTPS download origin for archive redirects. Repeat for multiple origins.") + var downloadOrigin: [String] = [] + + func access() throws -> HostedMarketplaceAccess? { + guard !tokenEnv.isEmpty || !downloadOrigin.isEmpty else { return nil } + var tokens: [URL: String] = [:] + for binding in tokenEnv { + let fields = binding.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false) + guard fields.count == 2, !fields[0].isEmpty, !fields[1].isEmpty else { + throw ValidationError( + "--token-env expects a user catalog name and variable as NAME=VARIABLE") + } + let catalog = try MarketplaceDirectory.lookup(String(fields[0]), scope: .user) + guard let index = catalog.origin.hostedIndex else { + throw ValidationError("--token-env requires a user-registered HTTPS index") + } + guard tokens[index] == nil else { + throw ValidationError("Supply only one token binding per HTTPS index") + } + guard let value = ProcessInfo.processInfo.environment[String(fields[1])], !value.isEmpty + else { + throw ValidationError("The specified token environment variable is empty or unset") + } + tokens[index] = value + } + let origins = try downloadOrigin.map { address in + guard let url = URL(string: address) else { throw ValidationError("Invalid download origin") } + return url + } + return try HostedMarketplaceAccess(trustedDownloadOrigins: origins) { [tokens] in tokens[$0] } + } +} + +struct RegisterMarketplace: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "register", abstract: "Save a named marketplace in this scope.") + @Argument var name: String + @OptionGroup var source: CatalogOptions + @OptionGroup var location: ScopeOptions + func run() throws { + try MarketplaceDirectory.register( + MarketplaceRegistration(name: name, origin: source.directOrigin()), scope: location.scope) + } +} + +struct ListMarketplaces: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "list", abstract: "List the marketplaces visible in this scope.") + @OptionGroup var location: ScopeOptions + func run() throws { + for entry in try MarketplaceDirectory.list(scope: location.scope) { + let origin = entry.registration.origin + let fields = [ + entry.registration.name, entry.scope.rawValue, origin.kind.rawValue, origin.location, + origin.ref, origin.subpath, + ] + Terminal.write(fields.compactMap { $0 }.map(Terminal.line).joined(separator: " ") + "\n") + } + } +} + +struct UnregisterMarketplace: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "unregister", abstract: "Remove a marketplace name from this scope.") + @Argument var name: String + @OptionGroup var location: ScopeOptions + func run() throws { try MarketplaceDirectory.unregister(name, scope: location.scope) } +} + +struct SearchMarketplace: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "search", abstract: "List package releases by name or summary.") + @OptionGroup var hosted: HostedAccessOptions + @OptionGroup var location: ScopeOptions + @Argument(help: "Optional package name or summary text.") var query: String? + @OptionGroup var source: CatalogOptions + + func run() throws { + let catalog = try MarketplaceOperations.browse( + source.registration(in: location.scope), scope: location.scope, hostedAccess: hosted.access()) + let releases = catalog.search(query ?? "") + for release in releases { + Terminal.write( + "\(Terminal.line(release.coordinate.package)) \(Terminal.line(release.coordinate.version)) \(Terminal.line(release.summary ?? ""))\n" + ) + } + if releases.isEmpty { Terminal.write("No matching packages.\n") } + } +} + +struct VerifyMarketplace: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "verify", abstract: "Verify the metadata and bundle of every marketplace release.") + @OptionGroup var hosted: HostedAccessOptions + @OptionGroup var location: ScopeOptions + @OptionGroup var source: CatalogOptions + + func run() throws { + let catalog = try MarketplaceOperations.verifyCatalog( + source.registration(in: location.scope), scope: location.scope, hostedAccess: hosted.access()) + for release in catalog.releases { + Terminal.write( + "\(Terminal.line(release.coordinate.package + "@" + release.coordinate.version)) \(release.archiveDigest)\n" + ) + } + Terminal.write("Verified releases: \(catalog.releases.count)\n") + } +} + +struct PublishPackage: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "publish", abstract: "Publish a bundle to a team marketplace directory.") + @Argument(help: "Verified portable bundle to publish.") var archive: String + @OptionGroup var source: CatalogOptions + @OptionGroup var location: ScopeOptions + @Option(help: "Short description for the catalog.") var summary: String? + + func run() throws { + let address = try source.registration(in: location.scope).origin + guard address.kind == .directory else { + throw ValidationError("Publishing requires a directory marketplace") + } + let published = try MarketplaceOperations.publishBundle( + Data(contentsOf: URL(fileURLWithPath: archive)), to: URL(fileURLWithPath: address.location), + summary: summary, scope: location.scope) + Terminal.write( + "\(Terminal.line(published.coordinate.package)) \(Terminal.line(published.coordinate.version)) \(published.archiveDigest)\n" + ) + } +} + +struct StageHostedMarketplace: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "stage", abstract: "Add a verified bundle to a local HTTPS marketplace export.") + @Argument(help: "Portable bundle file.") var archive: String + @Option(help: "Local static hosting directory.") var directory: String + @Option(help: "Short description for the catalog.") var summary: String? + + func run() throws { + let package = try AuthorPackageOperations.readArchive(at: URL(fileURLWithPath: archive)) + let index = try MarketplaceOperations.exportHostedBundle( + package.archive, to: URL(fileURLWithPath: directory), summary: summary) + Terminal.write(Terminal.line(index.path) + "\n") + } +} + +struct InstalledPackages: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "installed", abstract: "List this scope's locked marketplace packages.") + @OptionGroup var location: ScopeOptions + + func run() throws { + let inspection = try committedMarketplaceInspection(location.scope) + let pins = inspection.marketplacePackages + let graph = inspection.marketplaceGraph + for pin in pins { + let dependency = pin.dependency + Terminal.write( + "\(Terminal.line(dependency.name)) \(Terminal.line(dependency.coordinate.package)) \(Terminal.line(dependency.coordinate.version)) \(pin.archiveDigest)\n" + ) + } + if let graph { + let nodes = Dictionary(uniqueKeysWithValues: graph.nodes.map { ($0.id, $0) }) + for root in graph.roots { + guard let node = nodes[root.node] else { continue } + Terminal.write( + "\(Terminal.line(root.intent.name)) \(Terminal.line(node.coordinate.package)) \(Terminal.line(node.coordinate.version)) \(node.archiveDigest)\n" + ) + } + } + if pins.isEmpty && graph == nil { Terminal.write("No marketplace packages installed.\n") } + if let pending = inspection.pendingMarketplaceDeployment { + Terminal.write("Awaiting deployment: " + pending.digest + "\n") + if let desired = pending.graph { + MarketplaceOutput.roots(desired.roots) + for node in desired.nodes { + Terminal.write( + " " + Terminal.line(node.id.description) + " " + node.coordinate.version + "\n") + } + } else { + Terminal.write(" Remove all marketplace roots.\n") + } + } + } +} + +struct OutdatedPackages: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "outdated", abstract: "Check installed packages for newer releases.") + @OptionGroup var hosted: HostedAccessOptions + @OptionGroup var location: ScopeOptions + @Argument(help: "Installed dependency name. Omit to check all packages.") var name: String? + + func run() throws { + let scope = location.scope + let inspection = try committedMarketplaceInspection(scope) + let roots = (inspection.marketplaceGraph?.roots ?? []).filter { + name == nil || name == $0.intent.name + } + let pins = inspection.marketplacePackages.filter { name == nil || name == $0.dependency.name } + if let name, pins.isEmpty && roots.isEmpty { throw MarketplaceError.missingPin(name) } + for pin in pins { + let newer = try MarketplaceOperations.availableUpdates(for: pin, scope: scope) + let latest = newer.first?.coordinate.version ?? "No newer release" + Terminal.write( + "\(Terminal.line(pin.dependency.name)) \(Terminal.line(pin.dependency.coordinate.version)) \(Terminal.line(latest))\n" + ) + } + for root in roots { + let alias = root.intent.name + let report = try MarketplaceOperations.resolve( + .upgrade(alias), scope: scope, hostedAccess: hosted.access()) + Terminal.write("Root \(Terminal.line(alias))\n") + MarketplaceOutput.resolution(report, from: [root.node]) + } + if pins.isEmpty && roots.isEmpty { Terminal.write("No marketplace packages installed.\n") } + } +} + +struct UpgradeMarketPackage: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "upgrade", + abstract: "Review a newer release using this project's installed selections.") + @Argument(help: "Installed dependency name.") var name: String + @OptionGroup var hosted: HostedAccessOptions + @OptionGroup var version: MarketplaceVersionOptions + @OptionGroup var members: MarketplaceMemberOptions + @Flag(help: "Save the resolution and selected recipients for later deployment.") var lockOnly = + false + @OptionGroup var options: UpdateOptions + @OptionGroup var bindings: BindingOptions + + func run() async throws { + let scope = options.location.scope + let inspection = try committedMarketplaceInspection(scope) + let requirement = try version.requirement() + guard members.agent.isEmpty || !members.member.isEmpty else { + throw ValidationError("--agent on upgrade requires --member") + } + if lockOnly + || inspection.marketplaceGraph?.roots.contains(where: { $0.intent.name == name }) == true + || version.requirementExpression != nil || !members.member.isEmpty + { + try await options.finishMarketplace( + .upgrade(name, requirement: requirement, selections: try members.selections(in: scope)), + bindings: bindings, lockOnly: lockOnly, hostedAccess: hosted.access()) + return + } + guard let pin = inspection.marketplacePackages.first(where: { $0.dependency.name == name }) + else { + throw MarketplaceError.missingPin(name) + } + let newer = try MarketplaceOperations.availableUpdates(for: pin, scope: scope) + guard + let release = newer.first(where: { + version.packageVersion == nil || $0.coordinate.version == version.packageVersion + }) + else { + if let packageVersion = version.packageVersion { + throw MarketplaceError.releaseNotFound(name + "@" + packageVersion) + } + if options.json { + try Terminal.json(UpdateReport(scope: scope.rawValue, results: [])) + } else { + Terminal.write("No newer release for \(Terminal.line(name)).\n") + } + return + } + let verified = try MarketplaceOperations.acquire(release, scope: scope) + let bundle = try verified.inspectBundle() + if bundle.package.dependencies != nil { + try await options.finishMarketplace( + .upgrade(name, requirement: .exact(release.coordinate.version)), bindings: bindings, + hostedAccess: hosted.access()) + return + } + let selections = try bundle.retainedSelections(for: pin, in: inspection) + guard !selections.isEmpty else { + throw ValidationError( + "No installed components match this release. Choose its components with marketplace install." + ) + } + if options.apply { + let review = try verified.previewImportLifecycle( + as: name, selections: selections, intent: .update, scope: scope) + try await options.applyImport(review, bindings: bindings) + } else { + try options.showImport(verified.previewImport(as: name, selections: selections, scope: scope)) + } + } +} + +struct InstallMarketPackage: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "install", abstract: "Preview or apply a marketplace release to this scope.") + @Argument(help: "Package name in the marketplace.") var package: String + @OptionGroup var hosted: HostedAccessOptions + @OptionGroup var version: MarketplaceVersionOptions + @Option(help: "Name for this dependency in the declaration. Defaults to its package name.") + var alias: String? + @OptionGroup var source: CatalogOptions + @OptionGroup var members: MarketplaceMemberOptions + @Option(help: "Root entry ID from bundle inspect. Repeat for several entries.") + var component: [String] = [] + @Flag(help: "Record a root with no selected native components.") var metadataOnly = false + @Flag(help: "Replace conflicting instruction content shown by the preview.") var replace = false + @Flag(help: "Save the resolution and selected recipients for later deployment.") var lockOnly = + false + @OptionGroup var options: UpdateOptions + @OptionGroup var bindings: BindingOptions + + func validate() throws { + if lockOnly && replace { throw ValidationError("--replace applies during deployment") } + if metadataOnly { + guard members.agent.isEmpty, members.member.isEmpty, component.isEmpty else { + throw ValidationError("--metadata-only cannot be combined with component selections") + } + } else if members.agent.isEmpty { + throw ValidationError("Specify --agent or choose --metadata-only") + } + if !members.member.isEmpty && !component.isEmpty { + throw ValidationError("Choose either --component or --member") + } + _ = try version.requirement() + } + + func run() async throws { + let scope = options.location.scope + let name = alias ?? package + let registration = try source.registration(in: scope) + let access = try hosted.access() + let inspection = try UpdateOperations.inspect(scope: scope) + try requireCommittedInspection(inspection) + let existing = inspection.declaration?.marketplaceRoots.first { $0.name == name } + let requirement = try version.requirement() ?? existing?.requirement + // Exact leaf pins support upgrading to the newest release. Graph roots retain their constraint. + let useExactImport = + registration.origin.kind != .hosted && existing == nil && version.requirementExpression == nil + && !metadataOnly && !lockOnly + && members.member.isEmpty + && inspection.marketplaceGraph?.nodes.contains(where: { $0.id.package == package }) != true + let constraint: SourceRequirement + if let requirement, !useExactImport { + constraint = requirement + } else { + let release = try MarketplaceOperations.browse( + registration, scope: scope, hostedAccess: access + ).select( + package: package, version: version.packageVersion) + if useExactImport { + let verified = try MarketplaceOperations.acquire(release, scope: scope) + let contents = try verified.inspectBundle() + if contents.package.dependencies == nil { + let ids = component.isEmpty ? contents.components.map(\.id) : component + let selections = ids.map { + BundleImportSelection(componentID: $0, targets: members.agent) + } + if options.apply { + let review = try verified.previewImportLifecycle( + as: name, selections: selections, intent: .install, scope: scope, replace: replace) + try await options.applyImport(review, bindings: bindings) + } else { + try options.showImport( + verified.previewImport( + as: name, selections: selections, scope: scope, replace: replace)) + } + return + } + } + constraint = .exact(release.coordinate.version) + } + + func root(_ selections: [MarketplaceMemberSelection]) throws -> MarketplaceRoot { + try MarketplaceRoot( + name: name, catalog: registration.origin, package: package, requirement: constraint, + selections: selections) + } + if metadataOnly { + try await options.finishMarketplace( + .install(root([])), bindings: bindings, replace: replace, lockOnly: lockOnly, + hostedAccess: access) + } else if let selected = try members.selections(in: scope) { + try await options.finishMarketplace( + .install(root(selected)), bindings: bindings, replace: replace, lockOnly: lockOnly, + hostedAccess: access) + } else { + let discovery = try MarketplaceResolutionRequest.install(root([])) + let candidate: MarketplaceResolution + if lockOnly { + candidate = try MarketplaceOperations.previewLockOnly( + discovery, scope: scope, hostedAccess: access + ).resolution + } else { + candidate = try MarketplaceOperations.resolve(discovery, scope: scope, hostedAccess: access) + } + guard let available = candidate.rootMembers(named: name) else { + throw ValidationError("The selected release archive is unavailable for component discovery") + } + let selected = + try component.isEmpty + ? available + : component.map { id in + guard let item = available.first(where: { $0.id == id }) else { + throw ValidationError("Unknown bundle entry: " + Terminal.line(id)) + } + return item + } + let selections = try selected.map { + try MarketplaceMemberSelection( + package: package, member: $0.marketplaceKey, targets: members.agent) + } + try await options.finishMarketplace( + .install(root(selections)), bindings: bindings, replace: replace, lockOnly: lockOnly, + hostedAccess: access + ) { resolution in + guard resolution.rootMembers(named: name)?.map(\.id) == available.map(\.id) else { + throw ValidationError("Available package members changed. Run marketplace install again") + } + } + } + } +} + +struct RemoveMarketPackage: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "remove", abstract: "Preview or remove a package installed in this scope.") + @Argument(help: "Dependency name from marketplace installed.") var name: String + @Flag(help: "Save the resolution and selected recipients for later deployment.") var lockOnly = + false + @OptionGroup var hosted: HostedAccessOptions + @OptionGroup var options: UpdateOptions + @OptionGroup var bindings: BindingOptions + + func run() async throws { + let scope = options.location.scope + let inspection = try committedMarketplaceInspection(scope) + if lockOnly + || inspection.marketplaceGraph?.roots.contains(where: { $0.intent.name == name }) == true + { + try await options.finishMarketplace( + .remove(name), bindings: bindings, lockOnly: lockOnly, hostedAccess: hosted.access()) + return + } + let request = MarketplaceOperations.removalRequest(for: name) + if options.apply { + let review = try UpdateOperations.previewLifecycle(request, intent: .uninstall, scope: scope) + Terminal.updateDifferences(review.report, paths: options.location.paths) + try await applyLifecycle(review, scope: scope, bindingProvider: bindings.provider()) + } else { + let report = try UpdateOperations.preview(request, scope: scope) + if options.json { + try Terminal.json(UpdateReport(report)) + } else { + Terminal.updateDifferences(report, paths: options.location.paths) + options.previewNotice(changed: report.hasChanges) + } + } + } +} diff --git a/Sources/CLI/MarketplaceDeployment.swift b/Sources/CLI/MarketplaceDeployment.swift new file mode 100644 index 0000000..da1ecae --- /dev/null +++ b/Sources/CLI/MarketplaceDeployment.swift @@ -0,0 +1,95 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct MarketplacePendingReport: Encodable { + let schemaVersion = 1 + let resolution: MarketplaceResolutionReport + let pendingDigest: String + let changed: Bool + let policyFindings: [CheckItem] + + init(_ preview: MarketplaceLockPreview) { + resolution = MarketplaceResolutionReport(preview.resolution, scope: preview.report.scope) + pendingDigest = preview.report.pendingDeployment.digest + changed = preview.report.hasChanges + policyFindings = preview.report.organizationPolicy?.findings.map(CheckItem.init) ?? [] + } +} + +struct ResolvePendingMarketPackages: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "lock", abstract: "Resolve the package declaration for a later offline deployment." + ) + @OptionGroup var hosted: HostedAccessOptions + @OptionGroup var options: UpdateOptions + + func run() async throws { + try await options.finishPendingLock(.reconcile, hostedAccess: hosted.access()) + } +} + +extension UpdateOptions { + func finishPendingLock( + _ request: MarketplaceResolutionRequest, hostedAccess: HostedMarketplaceAccess? = nil, + checking check: (MarketplaceResolution) throws -> Void = { _ in } + ) async throws { + let review = + try apply + ? MarketplaceOperations.previewLockOnlyLifecycle( + request, intent: request.lifecycleIntent, scope: location.scope, hostedAccess: hostedAccess) + : nil + let preview = + try review?.report + ?? MarketplaceOperations.previewLockOnly( + request, scope: location.scope, hostedAccess: hostedAccess) + try check(preview.resolution) + if json { + try Terminal.json(MarketplacePendingReport(preview)) + } else { + MarketplaceOutput.resolution(preview.resolution) + if let change = preview.report.marketplaceGraphChange { MarketplaceOutput.changes(change) } + for finding in preview.report.organizationPolicy?.findings ?? [] { + Terminal.write(Terminal.line(finding.message) + "\n") + } + Terminal.write("Pending deployment: " + preview.report.pendingDeployment.digest + "\n") + } + if let review { + try await applyLifecycle(review, scope: location.scope) + } else if !json { + previewNotice(changed: preview.report.hasChanges) + } + } +} + +struct DeployLockedMarketPackages: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "deploy", abstract: "Deploy the selected recipients from the pending lock.") + @OptionGroup var options: UpdateOptions + @OptionGroup var bindings: BindingOptions + @Flag(help: "Replace conflicting instruction content shown by the preview.") var replace = false + + func run() async throws { + let scope = options.location.scope + if options.apply { + let review = try MarketplaceOperations.previewFrozenLifecycle( + intent: .install, scope: scope, replace: replace) + Terminal.updateDifferences(review.report, paths: options.location.paths) + if let conflict = review.ownershipConflict { throw CoreError.invalidState(conflict) } + try await applyLifecycle(review, scope: scope, bindingProvider: bindings.provider()) + } else { + let preview = try MarketplaceOperations.previewFrozenDeployment( + scope: scope, replace: replace) + if options.json { + try Terminal.json(UpdateReport(preview.report)) + } else { + Terminal.updateDifferences(preview.report, paths: options.location.paths) + } + if let conflict = preview.ownershipConflict { throw CoreError.invalidState(conflict) } + if !options.json { + options.previewNotice(changed: preview.report.hasChanges) + } + } + } +} diff --git a/Sources/CLI/MarketplaceGraphCommands.swift b/Sources/CLI/MarketplaceGraphCommands.swift new file mode 100644 index 0000000..251fe7f --- /dev/null +++ b/Sources/CLI/MarketplaceGraphCommands.swift @@ -0,0 +1,251 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct MarketplaceVersionOptions: ParsableArguments { + @Option(help: "Exact package release.") var packageVersion: String? + @Option( + name: .customLong("requirement"), + help: "Accepts VERSION, major:VERSION, minor:VERSION, or LOWER.. SourceRequirement? { + if let requirementExpression { + guard packageVersion == nil else { + throw ValidationError("Choose either --package-version or --requirement") + } + return try parseMarketplaceRequirement(requirementExpression) + } + return try packageVersion.map { try SourceRequirement.exact($0).canonicalized() } + } +} + +func parseMarketplaceRequirement(_ text: String) throws -> SourceRequirement { + let requirement: SourceRequirement + if text.hasPrefix("major:") { + requirement = .upToNextMajor(from: String(text.dropFirst("major:".count))) + } else if text.hasPrefix("minor:") { + requirement = .upToNextMinor(from: String(text.dropFirst("minor:".count))) + } else { + let bounds = text.components(separatedBy: "..<") + if bounds.count == 2 { + requirement = .range(from: bounds[0], to: bounds[1]) + } else { + requirement = .exact(text) + } + } + return try requirement.canonicalized() +} + +struct MarketplacePackageReference { + let package: String + let catalog: MarketplaceOrigin? + + init(_ text: String, scope: InstallScope) throws { + let fields = text.split(separator: ":", maxSplits: 1, omittingEmptySubsequences: false) + package = String(fields.last ?? "") + if fields.count == 2 { + catalog = try MarketplaceDirectory.lookup(String(fields[0]), scope: scope).origin + } else { + catalog = nil + } + } +} + +struct MarketplaceMemberOptions: ParsableArguments { + @Option( + help: "Destination client for each selected member. Repeat for multiple clients.", + transform: AgentID.parse) + var agent: [AgentID] = [] + @Option(help: "Select [CATALOG:]PACKAGE/KIND/NAME. Repeat for multiple members.") + var member: [String] = [] + + func selections(in scope: InstallScope) throws -> [MarketplaceMemberSelection]? { + guard !member.isEmpty else { return nil } + guard !agent.isEmpty else { throw ValidationError("--member requires --agent") } + let targets = Array(Set(agent)) + return try member.map { value in + let fields = value.split(separator: "/", maxSplits: 2, omittingEmptySubsequences: false) + guard fields.count == 3, let kind = DeclaredComponentKind(rawValue: String(fields[1])) else { + throw ValidationError("--member expects [CATALOG:]PACKAGE/KIND/NAME") + } + let reference = try MarketplacePackageReference(String(fields[0]), scope: scope) + return try MarketplaceMemberSelection( + package: reference.package, catalog: reference.catalog, + member: .init(kind: kind, name: String(fields[2])), targets: targets) + } + } +} + +struct ResolveMarketPackages: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "resolve", abstract: "Resolve package versions and members without applying.") + @Argument(help: "Prospective package. Omit to resolve the declared roots.") var package: String? + @Option(help: "Root alias for a prospective package. Defaults to its package name.") + var alias: String? + @OptionGroup var hosted: HostedAccessOptions + @OptionGroup var source: CatalogOptions + @OptionGroup var version: MarketplaceVersionOptions + @OptionGroup var location: ScopeOptions + @Flag(help: "Print the versioned JSON resolution.") var json = false + + func run() throws { + let scope = location.scope + let requirement = try version.requirement() + let access = try hosted.access() + let request: MarketplaceResolutionRequest + if let package { + let registration = try source.registration(in: scope) + let constraint: SourceRequirement + if let requirement { + constraint = requirement + } else { + let release = try MarketplaceOperations.browse( + registration, scope: scope, hostedAccess: access + ).select( + package: package) + constraint = .exact(release.coordinate.version) + } + request = .install( + try MarketplaceRoot( + name: alias ?? package, catalog: registration.origin, package: package, + requirement: constraint)) + } else { + guard !source.specified, requirement == nil, alias == nil else { + throw ValidationError("Catalog, release requirement and alias options need a package name") + } + request = .reconcile + } + let result = try MarketplaceOperations.resolve(request, scope: scope, hostedAccess: access) + if json { + try Terminal.json(MarketplaceResolutionReport(result, scope: scope)) + } else { + MarketplaceOutput.resolution(result, showMembers: true) + } + } +} + +struct MarketplaceDependencies: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "deps", abstract: "Show roots and edges from the committed dependency graph.") + @OptionGroup var location: ScopeOptions + + func run() throws { + let inspection = try committedMarketplaceInspection(location.scope) + if let graph = inspection.marketplaceGraph { + MarketplaceOutput.roots(graph.roots) + for node in graph.nodes { + Terminal.write( + "\(Terminal.line(node.id.description)) locked \(Terminal.line(node.coordinate.version))\n" + ) + MarketplaceOutput.edges(node.dependencies) + } + } + for pin in inspection.marketplacePackages { + let dependency = pin.dependency + let coordinate = dependency.coordinate + Terminal.write( + "Root \(Terminal.line(dependency.name)) \(coordinate.package)@\(coordinate.version)\n") + } + if inspection.marketplaceGraph == nil && inspection.marketplacePackages.isEmpty { + Terminal.write("No marketplace packages installed.\n") + } + } +} + +struct MarketplaceWhy: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "why", abstract: "Show which roots and packages require a locked package.") + @Argument(help: "Package name as shown by marketplace deps.") var package: String + @OptionGroup var location: ScopeOptions + + func run() throws { + let inspection = try committedMarketplaceInspection(location.scope) + let pins = inspection.marketplacePackages.filter { $0.dependency.coordinate.package == package } + for pin in pins { + let dependency = pin.dependency + let coordinate = dependency.coordinate + Terminal.write( + "\(coordinate.package)@\(coordinate.version) root \(Terminal.line(dependency.name))\n") + } + let graph = inspection.marketplaceGraph + let matches = (graph?.nodes ?? []).filter { $0.id.package == package } + guard !matches.isEmpty || !pins.isEmpty else { throw MarketplaceError.missingPin(package) } + guard let graph else { return } + for node in matches { + Terminal.write("\(Terminal.line(node.id.description)) \(node.coordinate.version)\n") + for root in graph.rootsRequiring(node.id) { + Terminal.write(" Required by root \(Terminal.line(root))\n") + } + for incoming in graph.incoming(to: node.id) { + Terminal.write( + " Required by \(Terminal.line(incoming.parent.description)) \(MarketplaceOutput.requirement(incoming.requirement.requirement))\n" + ) + } + } + } +} + +func committedMarketplaceInspection(_ scope: InstallScope) throws -> ScopeInspection { + let inspection = try UpdateOperations.inspect(scope: scope) + try requireCommittedInspection(inspection) + if let error = inspection.marketplaceIssue { throw error } + return inspection +} + +extension MarketplaceResolution { + func rootMembers(named name: String) -> [BundleComponent]? { + guard let root = roots.first(where: { $0.intent.name == name }) else { return nil } + return nodes.first { $0.versions.node == root.node }?.availableMembers + } +} + +extension MarketplaceResolutionRequest { + var lifecycleIntent: LifecycleOperationIntent { + switch self { + case .install: .install + case .upgrade, .reconcile: .update + case .remove: .uninstall + } + } +} + +extension UpdateOptions { + func finishMarketplace( + _ request: MarketplaceResolutionRequest, bindings: BindingOptions, replace: Bool = false, + lockOnly: Bool = false, hostedAccess: HostedMarketplaceAccess? = nil, + checking check: (MarketplaceResolution) throws -> Void = { _ in } + ) async throws { + if lockOnly { + try await finishPendingLock(request, hostedAccess: hostedAccess, checking: check) + return + } + let review = + try apply + ? MarketplaceOperations.previewResolutionLifecycle( + request, intent: request.lifecycleIntent, scope: location.scope, replace: replace, + hostedAccess: hostedAccess) + : nil + let preview = + try review?.report + ?? MarketplaceOperations.previewResolution( + request, scope: location.scope, replace: replace, hostedAccess: hostedAccess) + try check(preview.resolution) + if json { + try Terminal.json(MarketplacePreviewReport(preview)) + } else { + MarketplaceOutput.resolution(preview.resolution) + if let change = preview.report.marketplaceGraphChange { + MarketplaceOutput.changes(change) + } + Terminal.updateDifferences(preview.report, paths: location.paths) + } + if let conflict = preview.ownershipConflict { throw CoreError.invalidState(conflict) } + if let review { + try await applyLifecycle(review, scope: location.scope, bindingProvider: bindings.provider()) + } else if !json { + previewNotice(changed: preview.report.hasChanges) + } + } +} diff --git a/Sources/CLI/MarketplaceReports.swift b/Sources/CLI/MarketplaceReports.swift new file mode 100644 index 0000000..1630408 --- /dev/null +++ b/Sources/CLI/MarketplaceReports.swift @@ -0,0 +1,250 @@ +import AgentsCore +import AgentsUpdates + +struct MarketplaceResolutionReport: Encodable { + struct NodeID: Encodable { + let package: String + let catalogKind: String + let catalogOrigin: String + let hostedIndex: String? + let subpath: String? + + init(_ id: MarketplaceNodeID) { + package = id.package + catalogKind = id.catalog.kind.rawValue + catalogOrigin = id.catalog.origin.description + hostedIndex = id.catalog.hostedIndex?.absoluteString + subpath = id.catalog.subpath + } + } + + struct Root: Encodable { + let name: String + let node: NodeID + let requirement: String + let selections: [Selection] + + init(_ root: MarketplaceResolvedRoot) { + name = root.intent.name + node = NodeID(root.node) + requirement = MarketplaceOutput.requirement(root.intent.requirement) + selections = root.intent.selections.map(Selection.init) + } + } + + struct Selection: Encodable { + let package: String + let catalog: Catalog? + let kind: String + let name: String + let targets: [String] + + init(_ selection: MarketplaceMemberSelection) { + package = selection.package + catalog = selection.catalog.map(Catalog.init) + kind = selection.member.kind.rawValue + name = selection.member.name + targets = selection.targets.map(\.rawValue) + } + } + + struct Catalog: Encodable { + let kind: String + let location: String + let ref: String? + let subpath: String? + + init(_ origin: MarketplaceOrigin) { + kind = origin.kind.rawValue + location = origin.location + ref = origin.ref + subpath = origin.subpath + } + } + + struct Node: Encodable { + let id: NodeID + let catalog: Catalog + let locked: String? + let eligible: String + let latest: String? + let dependencies: [Edge] + let availableMembers: [Member]? + + init(_ node: MarketplaceResolutionNode) { + id = NodeID(node.versions.node) + catalog = Catalog(node.catalog) + locked = node.versions.locked?.version + eligible = node.versions.eligible.version + latest = node.versions.latest?.version + dependencies = node.dependencies.map(Edge.init) + availableMembers = node.availableMembers?.map(Member.init) + } + } + + struct Edge: Encodable { + let target: NodeID + let requirement: String + + init(_ edge: MarketplaceResolvedEdge) { + target = NodeID(edge.target) + requirement = MarketplaceOutput.requirement(edge.requirement.requirement) + } + } + + struct Member: Encodable { + let id: String + let kind: String + let name: String + + init(_ member: BundleComponent) { + id = member.id + kind = member.kind.rawValue + name = member.name + } + } + + let schemaVersion = 1 + let scope: String + let roots: [Root] + let nodes: [Node] + + init(_ result: MarketplaceResolution, scope: InstallScope) { + self.scope = scope.rawValue + roots = result.roots.map(Root.init) + nodes = result.nodes.map(Node.init) + } +} + +struct MarketplacePreviewReport: Encodable { + struct PinChange: Encodable { + let id: MarketplaceResolutionReport.NodeID + let before: String? + let after: String? + + init(_ id: MarketplaceNodeID, before: String?, after: String?) { + self.id = .init(id) + self.before = before + self.after = after + } + } + + let schemaVersion = 1 + let resolution: MarketplaceResolutionReport + let update: UpdateReport + let affectedRoots: [String] + let pinChanges: [PinChange] + let ownershipConflict: String? + + init(_ preview: MarketplaceResolutionPreview) { + resolution = MarketplaceResolutionReport(preview.resolution, scope: preview.report.scope) + update = UpdateReport(preview.report) + affectedRoots = preview.report.marketplaceGraphChange?.affectedRoots ?? [] + pinChanges = + preview.report.marketplaceGraphChange.map { change in + MarketplaceOutput.changedNodes(change).map { + PinChange( + $0.id, before: $0.before?.coordinate.version, after: $0.after?.coordinate.version) + } + } ?? [] + ownershipConflict = preview.ownershipConflict + } +} + +enum MarketplaceOutput { + static func requirement(_ requirement: SourceRequirement) -> String { + let text: String + switch requirement { + case .exact(let version): text = version + case .upToNextMajor(let lower): text = "major:" + lower + case .upToNextMinor(let lower): text = "minor:" + lower + case .range(let lower, let upper): text = lower + "..<" + upper + case .branch(let branch): text = "branch:" + branch + case .revision(let revision): text = "revision:" + revision + } + return Terminal.line(text) + } + + static func roots(_ roots: [MarketplaceResolvedRoot]) { + for root in roots { + Terminal.write( + "Root \(Terminal.line(root.intent.name)) \(Terminal.line(root.node.description)) \(requirement(root.intent.requirement))\n" + ) + for selection in root.intent.selections { + let catalog = selection.catalog.map { "\($0.location) / " } ?? "" + let member = + "\(catalog)\(selection.package)/\(selection.member.kind.rawValue)/\(selection.member.name)" + Terminal.write( + " \(Terminal.line(member)) → \(selection.targets.map(\.rawValue).joined(separator: ", "))\n" + ) + } + } + } + + static func edges(_ dependencies: [MarketplaceResolvedEdge]) { + for edge in dependencies { + Terminal.write( + " Requires \(Terminal.line(edge.target.description)) \(requirement(edge.requirement.requirement))\n" + ) + } + } + + static func resolution( + _ result: MarketplaceResolution, from startingNodes: [MarketplaceNodeID]? = nil, + showMembers: Bool = false + ) { + var reachable = Set() + if var pending = startingNodes { + let descendants = Dictionary( + uniqueKeysWithValues: result.nodes.map { ($0.versions.node, $0.dependencies.map(\.target)) } + ) + while let id = pending.popLast() { + if reachable.insert(id).inserted { pending += descendants[id] ?? [] } + } + } else { + roots(result.roots) + } + let nodes = result.nodes.filter { startingNodes == nil || reachable.contains($0.versions.node) } + for node in nodes { + let versions = node.versions + Terminal.write( + "\(Terminal.line(versions.node.description)) locked \(versions.locked?.version ?? "—") eligible \(versions.eligible.version) latest \(versions.latest?.version ?? "—")\n" + ) + edges(node.dependencies) + if showMembers { + for item in node.availableMembers ?? [] { + Terminal.write( + " Member \(item.kind.rawValue)/\(Terminal.line(item.name)) \(Terminal.line(item.id))\n" + ) + } + } + } + if nodes.isEmpty && showMembers { Terminal.write("No marketplace roots to resolve.\n") } + } + + static func changedNodes(_ change: MarketplaceGraphUpdate) -> [( + id: MarketplaceNodeID, before: MarketplaceResolvedNode?, after: MarketplaceResolvedNode? + )] { + let old = Dictionary(uniqueKeysWithValues: (change.before?.nodes ?? []).map { ($0.id, $0) }) + let new = Dictionary(uniqueKeysWithValues: (change.after?.nodes ?? []).map { ($0.id, $0) }) + return Set(old.keys).union(new.keys).sorted { $0.description < $1.description }.compactMap { + let before = old[$0] + let after = new[$0] + guard before?.coordinate != after?.coordinate || before?.archiveDigest != after?.archiveDigest + else { return nil } + return ($0, before, after) + } + } + + static func changes(_ change: MarketplaceGraphUpdate) { + if !change.affectedRoots.isEmpty { + Terminal.write( + "Affected roots \(change.affectedRoots.map(Terminal.line).joined(separator: ", "))\n") + } + for (id, before, after) in changedNodes(change) { + Terminal.write( + "Package \(Terminal.line(id.description)) \(before?.coordinate.version ?? "—") → \(after?.coordinate.version ?? "—")\n" + ) + } + } +} diff --git a/Sources/CLI/Options.swift b/Sources/CLI/Options.swift index cdec88a..6d88089 100644 --- a/Sources/CLI/Options.swift +++ b/Sources/CLI/Options.swift @@ -22,8 +22,8 @@ struct AgentOptions: ParsableArguments { @Option( name: .long, help: - "Limit to this agent: codex, claude-code, cursor, gemini-cli or opencode. Repeat for several. Default: all recipients.", - transform: AgentID.parse) + "Limit to this agent: codex, claude-code, cursor, gemini-cli, opencode, or antigravity. Repeat for several. Default: all recipients.", + transform: parseSkillAgent) var agent: [AgentID] = [] var recipients: [AgentID]? { @@ -35,8 +35,8 @@ struct AddAgentOptions: ParsableArguments { @Option( name: .long, help: - "Agent to install for: codex, claude-code, cursor, gemini-cli or opencode. Repeat for several. Default: the agents already recorded for this skill or source, else the declaration's agents, else codex and claude-code.", - transform: AgentID.parse) + "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.", + transform: parseSkillAgent) var agent: [AgentID] = [] var recipients: [AgentID]? { @@ -49,6 +49,14 @@ struct SourcePathOptions: ParsableArguments { var path: String? } +private func parseSkillAgent(_ value: String) throws -> AgentID { + let agent = try AgentID.parse(value) + guard agent.supportsSkills else { + throw ValidationError("\(agent.rawValue) does not support skills") + } + return agent +} + struct DiscoveryOptions: ParsableArguments { @OptionGroup var sourcePath: SourcePathOptions @@ -75,9 +83,7 @@ struct RequirementOptions: ParsableArguments { } if let requirement { do { - // Core's decoder validates the same requirement forms used by declarations. - _ = try JSONDecoder().decode( - SourceRequirement.self, from: JSONEncoder().encode(requirement)) + _ = try requirement.canonicalized() } catch { throw ValidationError("\(error)\nProvide a valid source requirement.") } diff --git a/Sources/CLI/PackageLifecycleApply.swift b/Sources/CLI/PackageLifecycleApply.swift new file mode 100644 index 0000000..b8e595d --- /dev/null +++ b/Sources/CLI/PackageLifecycleApply.swift @@ -0,0 +1,142 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Dispatch + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +func completedLifecycleSubmission(_ submission: LifecycleSubmission) throws -> Value { + switch submission { + case .alreadyRunning: + throw CoreError.invalidState("The reviewed lifecycle operation is already running.") + case .completed(let value): + return value + } +} + +func withLifecycleCancellation( + _ operation: @escaping @Sendable () async -> Value +) async -> (value: Value, interrupted: Bool) { + let interrupt = DispatchSource.makeSignalSource(signal: SIGINT) + let terminate = DispatchSource.makeSignalSource(signal: SIGTERM) + let previousInterrupt = signal(SIGINT, SIG_IGN) + let previousTerminate = signal(SIGTERM, SIG_IGN) + let task = Task { + let value = await operation() + return (value, Task.isCancelled) + } + for source in [interrupt, terminate] { + source.setEventHandler { task.cancel() } + source.resume() + } + defer { + interrupt.cancel() + terminate.cancel() + _ = signal(SIGINT, previousInterrupt) + _ = signal(SIGTERM, previousTerminate) + } + return await withTaskCancellationHandler { + await task.value + } onCancel: { + task.cancel() + } +} + +func previewAfterRecovery( + scope: InstallScope, _ preview: () throws -> Review +) throws -> Review { + do { + return try preview() + } catch CoreError.recoveryPending { + // A read-only review cannot repair a journal. Admit the scope's writer without applying + // an update, then prepare a fresh review before any lifecycle action can start. + do { + try UpdateOperations.withPreparedUpdate(UpdateRequest(operation: .restore), scope: scope) { + _ in + } + } catch CoreError.transactionRecovered(let path) { + Terminal.notice( + "Recovered interrupted transaction at \(HumanPaths().path(path)); retrying once.") + } + return try preview() + } +} + +func applyLifecycle( + _ review: LifecyclePackageReview, + scope: InstallScope, bindingProvider: (any RuntimeBindingProvider)? = nil, json: Bool = false, + completed: (Value, PackageLifecycleReport?) throws -> Void = { _, _ in } +) async throws { + let paths = HumanPaths(scope: scope) + let preview = LifecycleInspectionReport(scope: scope, inspection: review.lifecycle) + if !review.lifecycle.actions.isEmpty || !review.lifecycle.diagnostics.isEmpty { + if json { + LifecycleOutput.inspection(preview, paths: paths, write: Terminal.notice, showEmpty: false) + } else { + LifecycleOutput.inspection(preview, paths: paths, showEmpty: false) + } + } + let (submission, interrupted) = await withLifecycleCancellation { + await UpdateOperations.perform(review, bindingProvider: bindingProvider) + } + let result = try completedLifecycleSubmission(submission) + let report = PackageLifecycleReport( + result, diagnostics: review.lifecycle.diagnostics, interrupted: interrupted) + if let report { + let actions = report.pre + report.post + if json { + if case .failure = result.package.result { + LifecycleOutput.results(actions, paths: paths, write: Terminal.notice) + } + } else { + LifecycleOutput.results(actions, paths: paths) + } + } + + switch result.package.result { + case .success(let value): + if result.package.disposition == .rolledBack { + throw CoreError.invalidState("The package operation rolled back.") + } + if result.package.recovery.pending || result.package.disposition == .recoveryRequired { + if result.package.disposition == .committed { try completed(value, report) } + reportPackageDisposition(result.package) + throw CoreError.recoveryPending(result.package.recovery.diagnostic ?? "Recovery is pending") + } + try completed(value, report) + if interrupted { + Terminal.notice( + "Interrupted after package application (\(result.package.disposition.rawValue)).") + throw ExitCode.failure + } + case .failure(let error): + reportPackageDisposition(result.package, error: error) + throw error + } +} + +private func reportPackageDisposition( + _ completion: UpdateCompletion, error: (any Error)? = nil +) { + switch completion.disposition { + case .committed: + if !(error is UpdateApplyError) { + Terminal.notice("Package changes committed before the operation finished.") + } + case .rolledBack: + Terminal.notice("Package changes were rolled back.") + case .recoveryRequired, .unchanged: + break + } + if completion.recovery.pending, let diagnostic = completion.recovery.diagnostic { + Terminal.notice(diagnostic) + } + if completion.recoveredBeforePreparation { + Terminal.notice( + "Recovery finished before application. Review the package again before retrying.") + } +} diff --git a/Sources/CLI/PackageLifecycleCommands.swift b/Sources/CLI/PackageLifecycleCommands.swift new file mode 100644 index 0000000..ab1b03e --- /dev/null +++ b/Sources/CLI/PackageLifecycleCommands.swift @@ -0,0 +1,407 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +struct LifecycleCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "lifecycle", abstract: "Review and manage package lifecycle actions.", + subcommands: [ + ListLifecycle.self, ValidateLifecycle.self, InitLifecycle.self, TestLifecycle.self, + TrustLifecycle.self, UntrustLifecycle.self, TrustedLifecycleRoots.self, + ]) +} + +struct ListLifecycle: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "list", abstract: "List actions and their eligibility without running them.") + @OptionGroup var location: ScopeOptions + @Flag(help: "Print the versioned JSON report.") var json = false + + func run() throws { + let report = LifecycleInspectionReport( + scope: location.scope, inspection: LifecycleOperations.list(scope: location.scope)) + if json { + try Terminal.json(report) + } else { + LifecycleOutput.inspection(report, paths: location.paths) + } + if !report.ok { throw ExitCode.failure } + } +} + +struct ValidateLifecycle: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "validate", abstract: "Validate lifecycle declarations without running actions.") + @OptionGroup var location: ScopeOptions + @Flag(help: "Print the versioned JSON report.") var json = false + + func run() throws { + let report = LifecycleInspectionReport( + scope: location.scope, diagnostics: LifecycleOperations.validate(scope: location.scope)) + if json { + try Terminal.json(report) + } else if report.ok { + Terminal.write("Lifecycle declarations are valid.\n") + } else { + LifecycleOutput.inspection(report, paths: location.paths) + } + if !report.ok { throw ExitCode.failure } + } +} + +struct TestLifecycle: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "test", abstract: "Simulate an event or explicitly execute its eligible actions.") + @Argument(help: "Lifecycle event. Default: post-install.", transform: parseLifecycleEvent) + var event: LifecycleEvent = .postInstall + @OptionGroup var location: ScopeOptions + @Flag(help: "Execute the eligible actions shown by the simulation.") var execute = false + @Flag(help: "Print the versioned JSON report.") var json = false + + func run() async throws { + let review = LifecycleOperations.simulate(event, scope: location.scope) + let preview = LifecycleInspectionReport( + scope: location.scope, inspection: review.inspection, event: event) + if !execute { + if json { + try Terminal.json(preview) + } else { + LifecycleOutput.inspection(preview, paths: location.paths) + Terminal.write("Simulation only. Use --execute to run eligible actions.\n") + } + if !preview.ok { throw ExitCode.failure } + return + } + + if json { + LifecycleOutput.inspection(preview, paths: location.paths, write: Terminal.notice) + } else { + LifecycleOutput.inspection(preview, paths: location.paths) + } + let (submission, interrupted) = await withLifecycleCancellation { + await LifecycleOperations.executeTest(review) + } + let results = try completedLifecycleSubmission(submission) + let report = LifecycleInspectionReport( + scope: location.scope, inspection: review.inspection, event: event, results: results, + interrupted: interrupted) + if json { + try Terminal.json(report) + } else { + LifecycleOutput.results(report.results ?? [], paths: location.paths) + if interrupted { Terminal.write("Lifecycle test interrupted.\n") } + } + if !report.ok { throw ExitCode.failure } + } +} + +private func parseLifecycleEvent(_ value: String) throws -> LifecycleEvent { + guard let event = LifecycleEvent(rawValue: value) else { + throw ValidationError( + "Choose a lifecycle event: " + + LifecycleEvent.allCases.map(\.rawValue) + .joined(separator: ", ")) + } + return event +} + +struct InitLifecycle: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "init", abstract: "Review or add starter events to an existing declaration.") + @OptionGroup var location: ScopeOptions + @Flag(help: "Save the reviewed starter declaration.") var apply = false + @Flag(help: "Replace an existing lifecycle declaration with starter events.") var force = false + @Option(help: "Require the proposed document digest from an earlier scaffold preview.") + var reviewedDigest: String? + @Option(help: "Require the original document digest from the same preview.") + var reviewedOriginalDigest: String? + @Flag(help: "Print the versioned JSON report.") var json = false + + func validate() throws { + if reviewedDigest != nil && !apply { + throw ValidationError("--reviewed-digest requires --apply") + } + if reviewedOriginalDigest != nil && reviewedDigest == nil { + throw ValidationError("--reviewed-original-digest requires --reviewed-digest") + } + if force && reviewedDigest != nil && reviewedOriginalDigest == nil { + throw ValidationError("A reviewed replacement requires --reviewed-original-digest") + } + } + + func run() async throws { + let review = try LifecycleOperations.previewScaffold(scope: location.scope, force: force) + let change = review.documentChange + var report = LifecycleScaffoldReport( + scope: location.scope.rawValue, path: review.destination.path, digest: change.digest, + originalDigest: change.originalDigest, + declaration: review.declaration.map(LifecycleDeclarationJSON.init)) + if json && !apply { + try Terminal.json(report) + return + } + func write(_ line: String) { + if json { Terminal.notice(line) } else { LifecycleOutput.writeLine(line) } + } + let verb = + force ? "Replace lifecycle with starter events in" : "Add lifecycle starter events in" + write("\(verb) \(location.paths.path(report.path))") + try report.declaration?.display(write: write) + write("Original digest \(report.originalDigest)") + write("Digest \(report.digest)") + guard apply else { + write("Preview only. Run again with --apply to save the starter events.") + return + } + if let reviewedDigest { + guard reviewedDigest == report.digest, + reviewedOriginalDigest == nil || reviewedOriginalDigest == report.originalDigest + else { + throw CoreError.invalidState( + "The document differs from the reviewed scaffold. Review it again.") + } + } + _ = try completedLifecycleSubmission(await LifecycleOperations.save(review)).get() + report.saved = true + if json { + try Terminal.json(report) + } else { + Terminal.write("Saved lifecycle scaffold.\n") + } + } +} + +struct TrustLifecycle: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "trust", abstract: "Review or grant trust to the current project declaration.") + @Flag(help: "Grant trust to the reviewed project actions.") var apply = false + @Option(help: "Require the project lifecycle digest from an earlier review.") + var reviewedDigest: String? + @Option(help: "Require the physical root ID from the same review.") var reviewedRoot: String? + @Option(help: "Require the receipt revision from the same review.") var reviewedRevision: UInt64? + @Flag(help: "Print the versioned JSON report.") var json = false + + func validate() throws { + let any = reviewedDigest != nil || reviewedRoot != nil || reviewedRevision != nil + if any && (!apply || reviewedDigest == nil || reviewedRoot == nil || reviewedRevision == nil) { + throw ValidationError( + "Supply --apply, --reviewed-digest, --reviewed-root and --reviewed-revision together") + } + } + + func run() async throws { + let review = try LifecycleOperations.reviewEnable() + let enablement = review.enablement + let rootID = try rootIdentifier(enablement.project) + var report = LifecycleTrustReviewReport( + path: enablement.project.canonicalPath, rootID: rootID, digest: enablement.digest, + revision: enablement.expectedRevision, notice: enablement.shellAccessNotice, + declaration: LifecycleDeclarationJSON(enablement.declaration)) + if json && !apply { + try Terminal.json(report) + return + } + func write(_ line: String) { + if json { Terminal.notice(line) } else { LifecycleOutput.writeLine(line) } + } + write("Review project lifecycle actions in \(Terminal.line(report.path))") + try report.declaration.display(write: write) + write(report.notice) + write("Digest \(report.digest)") + write("Root ID \(report.rootID)") + write("Receipt revision \(report.revision)") + guard apply else { + write("Preview only. Run again with --apply to grant trust.") + return + } + if let reviewedDigest { + guard reviewedDigest == report.digest, reviewedRoot == rootID, + reviewedRevision == report.revision + else { + throw CoreError.invalidState( + "The project lifecycle, physical root or trust receipt changed. Review it again.") + } + } else { + guard !json, isatty(STDIN_FILENO) == 1, isatty(STDOUT_FILENO) == 1 else { + throw ValidationError( + "Noninteractive trust requires --reviewed-digest, --reviewed-root and --reviewed-revision" + ) + } + Terminal.write("Trust these project actions? [y/N] ") + guard let answer = readLine()?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased(), + ["y", "yes"].contains(answer) + else { + Terminal.write("Trust grant cancelled.\n") + return + } + } + + let receipt = try completedLifecycleSubmission(await LifecycleOperations.enable(review)).get() + report.applied = true + report.revision = receipt.revision + if json { + try Terminal.json(report) + } else { + Terminal.write("Trusted project lifecycle actions.\n") + } + } +} + +struct TrustedLifecycleRoots: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "trusted", abstract: "List stored trust grants, including absent project roots.") + @Flag(help: "Print the versioned JSON report.") var json = false + + func run() throws { + let roots = try LifecycleOperations.storedTrust().filter { $0.digest != nil } + .map(LifecycleRootItem.init) + if json { + try Terminal.json(LifecycleRootsReport(roots: roots)) + } else if roots.isEmpty { + Terminal.write("No trusted lifecycle roots.\n") + } else { + for root in roots { Terminal.write(root.summary + "\n") } + } + } +} + +struct UntrustLifecycle: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "untrust", abstract: "Revoke a stored trust grant by path or physical root ID.") + @Argument(help: "Stored project path. Defaults to the current directory.") var path: String? + @Option(help: "Exact ID from lifecycle trusted, including a deleted or replaced root.") + var rootID: String? + @Flag(help: "Print the versioned JSON report.") var json = false + + func validate() throws { + if rootID != nil && path != nil { throw ValidationError("Choose a path or --root-id") } + } + + func run() throws { + let environment = RuntimeEnvironment() + let stored = try LifecycleOperations.storedTrust(environment: environment) + .filter { $0.digest != nil } + let url = + path.map { URL(fileURLWithPath: $0, relativeTo: environment.projectDirectory) } + ?? environment.projectDirectory + let canonicalPath = url.standardizedFileURL.resolvingSymlinksInPath().path + let matches = try stored.filter { record in + if let rootID { return try rootIdentifier(record.project) == rootID } + return record.project.canonicalPath.utf8.elementsEqual(canonicalPath.utf8) + } + guard matches.count == 1, let selected = matches.first else { + if matches.isEmpty { throw CoreError.notFound("lifecycle trust grant") } + throw ValidationError("Multiple grants match this path. Choose an ID from lifecycle trusted.") + } + let root = try LifecycleRootItem(selected) + let message = "Revoking lifecycle trust for " + root.summary + if json { Terminal.notice(message) } else { Terminal.write(message + "\n") } + let receipt = try LifecycleOperations.revoke(selected.project, environment: environment) + if json { + try Terminal.json( + LifecycleRootsReport( + kind: "lifecycle-untrust", + roots: [ + LifecycleRootItem(receipt) + ])) + } else { + Terminal.write("Revoked project lifecycle trust.\n") + } + } +} + +private struct LifecycleScaffoldReport: Encodable { + let schemaVersion = 1 + let kind = "lifecycle-init" + let scope: String + let path: String + let digest: String + let originalDigest: String + let declaration: LifecycleDeclarationJSON? + var saved = false +} + +private struct LifecycleTrustReviewReport: Encodable { + let schemaVersion = 1 + let kind = "lifecycle-trust" + let path: String + let rootID: String + let digest: String + var revision: UInt64 + let notice: String + let declaration: LifecycleDeclarationJSON + var applied = false +} + +private struct LifecycleRootsReport: Encodable { + let schemaVersion = 1 + var kind = "lifecycle-trusted" + let roots: [LifecycleRootItem] +} + +private struct LifecycleRootItem: Encodable { + let path: String + let rootID: String + let revision: UInt64 + let digest: String? + let pathExists: Bool + + init(_ record: LifecycleTrustRecord) throws { + path = record.project.canonicalPath + rootID = try rootIdentifier(record.project) + revision = record.revision + digest = record.digest + pathExists = FileManager.default.fileExists(atPath: path) + } + + var summary: String { + "\(Terminal.line(path))\(pathExists ? "" : " (path absent)") · \(rootID)" + } +} + +private func rootIdentifier(_ project: LifecycleProjectIdentity) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return try encoder.encode(project).base64EncodedString() +} + +/// The authored lifecycle subtree contains native declaration values. +private struct LifecycleDeclarationJSON: Encodable { + let value: DeclarationValue + + init(_ value: DeclarationValue) { self.value = value } + + func encode(to encoder: any Encoder) throws { + var output = encoder.singleValueContainer() + switch value { + case .string(let text): try output.encode(text) + case .integer(let number): try output.encode(number) + case .boolean(let flag): try output.encode(flag) + case .null: try output.encodeNil() + case .array(let items): try output.encode(items.map(Self.init)) + case .dictionary(let fields): try output.encode(fields.mapValues(Self.init)) + case .record, .requirement: + throw CoreError.invalidState("The lifecycle declaration contains a non-native value.") + } + } + + func display(write: (String) -> Void) throws { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] + let text = String(decoding: try encoder.encode(self), as: UTF8.self) + for line in Terminal.splitLines(text) { + let escaped = line.unicodeScalars.map { scalar in + scalar.properties.generalCategory == .format + ? "\\u{\(String(scalar.value, radix: 16))}" : String(scalar) + }.joined() + write(Terminal.line(escaped)) + } + } +} diff --git a/Sources/CLI/PackageLifecycleReports.swift b/Sources/CLI/PackageLifecycleReports.swift new file mode 100644 index 0000000..79c94f0 --- /dev/null +++ b/Sources/CLI/PackageLifecycleReports.swift @@ -0,0 +1,198 @@ +import AgentsCore +import AgentsUpdates +import Foundation + +struct LifecycleDiagnosticItem: Encodable { + let authority: String + let path: String + let event: String? + let index: Int? + let field: String? + let message: String + + init(_ diagnostic: LifecycleDiagnostic) { + authority = diagnostic.source.authority.rawValue + path = diagnostic.source.file.path + event = diagnostic.event + index = diagnostic.index + field = diagnostic.field + message = diagnostic.message + } + + func summary(paths: HumanPaths) -> String { + let location = [ + paths.path(path), event, index.map { "[\($0)]" }, field, + ].compactMap { $0 }.joined(separator: " ") + return "Lifecycle \(authority) \(location) · \(message)" + } +} + +struct LifecycleActionItem: Encodable { + let authority: String + let path: String + let event: String + let index: Int + let kind: String + let target: String + let timeoutSeconds: Int + let withholding: String? + + init(_ action: LifecycleActionSummary) { + authority = action.source.authority.rawValue + path = action.source.file.path + event = action.event.rawValue + index = action.index + kind = action.kind.rawValue + target = action.target + timeoutSeconds = action.timeoutSeconds + withholding = action.withheld?.rawValue + } + + func label(paths: HumanPaths) -> String { + "\(event)[\(index)] · \(authority) \(paths.path(path)) · \(kind) \(target)" + } +} + +struct LifecycleResultItem: Encodable { + let action: LifecycleActionItem + let status: String + let dispatched: Bool + let withholding: String? + let exitStatus: Int32? + let signal: Int32? + let httpStatus: Int? + let stdoutBytes: Int + let stderrBytes: Int + let processGroupCleanedUp: Bool? + let diagnostics: [LifecycleDiagnosticItem] + + init(_ result: LifecycleActionResult) { + action = LifecycleActionItem(result.action) + status = result.disposition.rawValue + dispatched = result.dispatched + withholding = result.withholding?.rawValue + exitStatus = result.exitStatus + signal = result.signal + httpStatus = result.httpStatus + stdoutBytes = result.stdoutBytes + stderrBytes = result.stderrBytes + processGroupCleanedUp = result.processGroupCleanedUp + diagnostics = result.diagnostics.map(LifecycleDiagnosticItem.init) + } + + func summary(paths: HumanPaths) -> String { + let details = [ + withholding, + exitStatus.map { "exit \($0)" }, + signal.map { "signal \($0)" }, + httpStatus.map { "HTTP \($0)" }, + processGroupCleanedUp == false ? "process group cleanup incomplete" : nil, + ].compactMap { $0 } + let suffix = details.isEmpty ? "" : " (" + details.joined(separator: ", ") + ")" + return "Lifecycle \(action.label(paths: paths)) · \(status)\(suffix)" + } +} + +struct LifecycleInspectionReport: Encodable { + let schemaVersion = 1 + let kind: String + let scope: String + let ok: Bool + var event: String? + var project: String? + var projectTrusted: Bool? + var allStartsWithheld: String? + var actions: [LifecycleActionItem]? + let diagnostics: [LifecycleDiagnosticItem] + var results: [LifecycleResultItem]? + var interrupted: Bool? + + init(scope: InstallScope, diagnostics: [LifecycleDiagnostic]) { + kind = "lifecycle-validation" + self.scope = scope.rawValue + self.diagnostics = diagnostics.map(LifecycleDiagnosticItem.init) + ok = diagnostics.isEmpty + } + + init( + scope: InstallScope, inspection: LifecycleInspection, event: LifecycleEvent? = nil, + results: [LifecycleActionResult]? = nil, interrupted: Bool = false + ) { + kind = event == nil ? "lifecycle-list" : "lifecycle-test" + self.scope = scope.rawValue + self.event = event?.rawValue + project = inspection.project?.canonicalPath + projectTrusted = inspection.project.map { _ in inspection.projectTrusted } + allStartsWithheld = inspection.allStartsWithheld?.rawValue + actions = inspection.actions.map(LifecycleActionItem.init) + diagnostics = inspection.diagnostics.map(LifecycleDiagnosticItem.init) + self.results = results?.map(LifecycleResultItem.init) + self.interrupted = interrupted ? true : nil + ok = diagnostics.isEmpty && !interrupted && (results?.allSatisfy(\.testSucceeded) ?? true) + } +} + +extension LifecycleActionResult { + fileprivate var testSucceeded: Bool { + switch disposition { + case .commandSucceeded: processGroupCleanedUp != false + case .httpSucceeded: true + default: false + } + } +} + +struct PackageLifecycleReport: Encodable { + let disposition: String + let interrupted: Bool? + let recoveryPending: Bool? + let pre: [LifecycleResultItem] + let post: [LifecycleResultItem] + let diagnostics: [LifecycleDiagnosticItem] + + init?( + _ result: LifecycleInvocationResult, diagnostics: [LifecycleDiagnostic], + interrupted: Bool + ) { + let pending = result.package.recovery.pending || result.package.disposition == .recoveryRequired + guard + !result.pre.isEmpty || !result.post.isEmpty || !diagnostics.isEmpty || interrupted || pending + else { return nil } + disposition = result.package.disposition.rawValue + self.interrupted = interrupted ? true : nil + recoveryPending = pending ? true : nil + pre = result.pre.map(LifecycleResultItem.init) + post = result.post.map(LifecycleResultItem.init) + self.diagnostics = diagnostics.map(LifecycleDiagnosticItem.init) + } +} + +enum LifecycleOutput { + static func writeLine(_ text: String) { Terminal.write(Terminal.line(text) + "\n") } + + static func inspection( + _ report: LifecycleInspectionReport, paths: HumanPaths, + write: (String) -> Void = LifecycleOutput.writeLine, showEmpty: Bool = true + ) { + for diagnostic in report.diagnostics { write(diagnostic.summary(paths: paths)) } + if let withholding = report.allStartsWithheld { + write("Lifecycle starts withheld (\(withholding)).") + } + guard let actions = report.actions else { return } + for action in actions { + let status = action.withholding.map { "withheld (\($0))" } ?? "eligible" + write("Lifecycle \(action.label(paths: paths)) · \(status) · \(action.timeoutSeconds)s") + } + if showEmpty && actions.isEmpty { write("No lifecycle actions found.") } + } + + static func results( + _ results: [LifecycleResultItem], paths: HumanPaths, + write: (String) -> Void = LifecycleOutput.writeLine + ) { + for result in results { + write(result.summary(paths: paths)) + for diagnostic in result.diagnostics { write(diagnostic.summary(paths: paths)) } + } + } +} diff --git a/Sources/CLI/PolicyCommand.swift b/Sources/CLI/PolicyCommand.swift new file mode 100644 index 0000000..5ae6375 --- /dev/null +++ b/Sources/CLI/PolicyCommand.swift @@ -0,0 +1,99 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import ArgumentParser +import Foundation + +struct PolicyCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "policy", abstract: "Inspect organization policy and configure allowed sources.", + subcommands: [ + ShowSourcePolicy.self, SetSourcePolicy.self, OrganizationPolicyStatusCommand.self, + ]) +} + +struct ShowSourcePolicy: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "show", abstract: "Show the policy layers that apply to this scope.") + @OptionGroup var location: ScopeOptions + @Flag(help: "Write the effective policy as JSON.") var json = false + + func run() throws { + let inspection = try SourcePolicyOperations.inspect(scope: location.scope) + if json { + try Terminal.json(inspection.effective) + return + } + if inspection.effective.layers.isEmpty { Terminal.write("No source policy configured.\n") } + for layer in inspection.effective.layers { + Terminal.write("\(layer.scope.rawValue) \(Terminal.line(layer.url.path))\n") + let yaml = try SourcePolicyDocument.bytes(for: layer.rules) + Terminal.write(String(decoding: yaml, as: UTF8.self) + "\n") + } + } +} + +struct SetSourcePolicy: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "set", abstract: "Preview or apply source policy YAML for one scope.") + @Argument(help: "Path to the policy YAML file.") var file: String + @OptionGroup var location: ScopeOptions + @Flag(help: "Save this policy.") var apply = false + + func run() throws { + let editor = try SourcePolicyEditor(scope: location.scope) + let bytes = try Data(contentsOf: URL(fileURLWithPath: file)) + _ = try SourcePolicyDocument.parse(bytes, identity: DocumentIdentity(file)) + if apply { + try editor.save(bytes) + Terminal.write("Saved policy to \(Terminal.line(editor.url.path)).\n") + } else if bytes == editor.original { + Terminal.write("Policy is up to date.\n") + } else { + Terminal.write("Proposed policy for \(Terminal.line(editor.url.path)):\n") + Terminal.write(String(decoding: bytes, as: UTF8.self) + "\n") + Terminal.write("Run again with --apply to save.\n") + } + } +} + +struct OrganizationPolicyStatusCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "status", abstract: "Show effective organization policy and its findings.") + @OptionGroup var location: ScopeOptions + @Flag(help: "Write policy evidence and findings as JSON.") var json = false + + func run() throws { + let audit = try OrganizationPolicyOperations.audit(scope: location.scope) + if json { + try Terminal.json(audit) + } else { + if audit.organization.policies.isEmpty { + Terminal.write("No organization policy selected.\n") + } + for policy in audit.organization.policies { + Terminal.write("\(policy.authority.rawValue) \(policy.outcome.rawValue)\n") + for document in policy.documents { + Terminal.write(" \(Terminal.line(document.url.absoluteString)) \(document.digest)\n") + } + } + for finding in audit.organization.findings { + Terminal.write( + "\(finding.outcome.rawValue) \(Terminal.line(finding.rule)) \(Terminal.line(finding.identity)) \(Terminal.line(finding.message))\n" + ) + } + if audit.pendingMarketplaceDeployment { + Terminal.write("The package lock is awaiting deployment.\n") + for finding in audit.pendingMarketplacePolicy?.findings ?? [] { + let check = CheckItem(finding) + Terminal.write(" " + check.status + " " + Terminal.line(check.message) + "\n") + } + } + if let issue = audit.closureIssue { Terminal.write(Terminal.line(issue) + "\n") } + for finding in audit.sourceViolations { + Terminal.write(Terminal.line(CheckItem(finding).message) + "\n") + } + } + if audit.isBlocked { throw ExitCode.failure } + } +} diff --git a/Sources/CLI/SkillCommands.swift b/Sources/CLI/SkillCommands.swift index 9909e8a..a75c051 100644 --- a/Sources/CLI/SkillCommands.swift +++ b/Sources/CLI/SkillCommands.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsSkills +import AgentsUpdates import ArgumentParser import Foundation @@ -71,12 +72,10 @@ struct ListSkills: ParsableCommand { func run() throws { if let source { - let outcome = try withRecovery { - try SkillOperations.add( - AddOptions( - source: source, agents: agents.recipients, scope: location.scope, listOnly: true, - fullDepth: discovery.fullDepth, path: discovery.path)) - } + let outcome = try SkillOperations.add( + AddOptions( + source: source, agents: agents.recipients, scope: location.scope, listOnly: true, + fullDepth: discovery.fullDepth, path: discovery.path)) if json { try Terminal.json( SourceListReport(scope: location.scope.rawValue, outcome: outcome)) @@ -84,9 +83,8 @@ struct ListSkills: ParsableCommand { Terminal.available(outcome.availableSkills) } } else { - let skills = try withRecovery { - try SkillOperations.listManaged(scope: location.scope, agents: agents.recipients) - } + let skills = try SkillOperations.listManaged( + scope: location.scope, agents: agents.recipients) if json { try Terminal.json(InstalledListReport(scope: location.scope.rawValue, skills: skills)) } else if skills.isEmpty { @@ -102,7 +100,7 @@ struct ListSkills: ParsableCommand { } } -struct Remove: ParsableCommand { +struct Remove: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "remove", abstract: "Remove declared skills and their installations.") @@ -114,14 +112,20 @@ struct Remove: ParsableCommand { if names.isEmpty { throw ValidationError("Specify at least one skill name") } } - func run() throws { - let (removed, previous) = try withRecovery { - let previous = SkillOutputInventory.read(scope: location.scope, agents: agents.recipients) - let removed = try SkillOperations.remove( - skillNames: names, scope: location.scope, agents: agents.recipients) - return (removed, previous) + func run() async throws { + let selectedNames = names.map(PathSafety.sanitizeName) + let request = UpdateRequest( + operation: .remove, kinds: [.skills], names: selectedNames, agents: agents.recipients) + let review = try previewAfterRecovery(scope: location.scope) { + try UpdateOperations.previewLifecycle(request, intent: .uninstall, scope: location.scope) + } + guard Set(selectedNames).isSubset(of: Set(review.report.skills.map(\.skill))) else { + throw CoreError.notFound("skill is not installed") + } + let previous = SkillOutputInventory.read(scope: location.scope, agents: agents.recipients) + try await applyLifecycle(review, scope: location.scope) { _, _ in + Terminal.removedSkills(selectedNames, previous: previous) } - Terminal.removedSkills(removed, previous: previous) } } diff --git a/Sources/CLI/SkillRendering.swift b/Sources/CLI/SkillRendering.swift index ccde15b..3ab8403 100644 --- a/Sources/CLI/SkillRendering.swift +++ b/Sources/CLI/SkillRendering.swift @@ -189,22 +189,7 @@ struct SkillOutputInventory { static func read(scope: InstallScope, agents: [AgentID]? = nil) -> Self { // Mutation owns recovery; withRecovery captures this snapshot again on retry. - if let installations = try? SkillOperations.listManaged(scope: scope, agents: agents) { - var result = Self() - for install in installations { - result.modes[install.name, default: [:]][install.agent.rawValue] = install.mode - } - return result - } - // Inventory hashes installed content, so unrelated unreadable content can fail - // it even when a removal succeeds. Locked recipients remain - // useful for presentation; read them without triggering state recovery. - let url = StateStore(scope: scope).resolvedURL - guard let metadata = try? url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]), - metadata.isRegularFile == true, metadata.isSymbolicLink != true, - let data = try? Data(contentsOf: url), - let lock = try? JSONDecoder().decode(ResolvedState.self, from: data) - else { return Self() } + guard let lock = try? StateStore(scope: scope).loadResolved() else { return Self() } return Self( modes: lock.skills.mapValues { skill in skill.installs.filter { raw, _ in diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index e022d86..5a91ec0 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import AgentsSkills import AgentsUpdates import ArgumentParser @@ -39,7 +40,7 @@ enum Terminal { } return text } - var lines = message.components(separatedBy: "\n") + var lines = splitLines(message) while let last = lines.last, last.allSatisfy({ " \t\r".contains($0) }) { lines.removeLast() } @@ -69,7 +70,12 @@ enum Terminal { } static func text(_ text: String) -> String { - text.components(separatedBy: "\n").map(line).joined(separator: "\n") + splitLines(text).map(line).joined(separator: "\n") + } + + /// Splits physical LF scalars, retaining CR content, empty lines and the trailing empty segment. + static func splitLines(_ text: String) -> [String] { + text.unicodeScalars.split(separator: "\n", omittingEmptySubsequences: false).map { String($0) } } static func failureRemedy(_ error: Error, command: any ParsableCommand) -> String { @@ -79,6 +85,19 @@ enum Terminal { } let action: String switch error { + case is ManifestFailure: + action = "fix the reported agents.yaml diagnostics and retry" + case CoreError.recoveryPending(let message) + where message.hasPrefix("Unresolved transaction conflict"): + action = "inspect the retained locations and resolve the transaction conflict before retrying" + case CoreError.recoveryPending: + action = + "run 'agents install' in the same scope (add --scope user for user state) to finish recovery" + case CoreError.missingDeclaration: + action = "restore agents.yaml from version control before retrying" + case CoreError.notFound where command is DumpManifest: + action = + "create agents.yaml in the selected scope before running 'agents manifest dump --json'" case CoreError.transactionRecovered: action = "retry the command after other writers finish" case CoreError.notFound(let message) where message.hasPrefix("source is not subscribed:"): @@ -104,7 +123,7 @@ enum Terminal { case CoreError.invalidSkill: action = "check SKILL.md and existing installations with 'agents doctor'" case CoreError.invalidState: - action = "check the scope's agents.json, agents.resolved, and recovery journal" + action = "check the scope's agents.yaml, agents.resolved, and recovery journal" case CoreError.commandFailed: action = "check the command arguments and filesystem permissions" case InstructionError.unownedTargets: @@ -126,14 +145,18 @@ enum Terminal { case InstructionError.invalidLinks: action = "link only to files in the checkout being written, or name the file in text without a link" + case InstructionError.antigravityConflicts: + action = "resolve the reported rule conflicts before retrying" case HumanOutputError.undeclaredPrompt: action = - "declare it under instructions.chatgpt in agents.json and run 'agents instructions update --apply'" + "declare it under chatgpt in the instructions component of agents.yaml and run 'agents instructions update --apply'" case InstructionError.emptyPrompt: action = - "declare the ChatGPT prompt in agents.json and run 'agents instructions update --apply'" + "declare the ChatGPT prompt in agents.yaml and run 'agents instructions update --apply'" case is InstructionError: action = "check the instruction source and target Markdown with 'agents doctor'" + case is SourceAccessSettingsError: + action = "review your source access settings and retry" default: action = "check the command arguments and filesystem permissions" } @@ -141,8 +164,24 @@ enum Terminal { } static func failureMessage(_ error: Error) -> String { - guard let error = error as? UpdateApplyError else { return String(describing: error) } - return updateFailureMessage(error.disposition, underlyingError: error.underlyingError) + if let cache = error as? AcquisitionCacheError { return cache.localizedDescription } + if let source = error as? SourceAccessError { return source.localizedDescription } + if let settings = error as? SourceAccessSettingsError { return settings.localizedDescription } + if let error = error as? UpdateApplyError { + return updateFailureMessage(error.disposition, underlyingError: error.underlyingError) + } + if let failure = error as? ManifestFailure { + return failure.diagnostics.map { diagnostic in + let span = diagnostic.span + let primary = + "\(span.document.rawValue):\(span.line):\(span.column): \(diagnostic.severity.rawValue) [\(diagnostic.code)]: \(diagnostic.message)" + let related = diagnostic.related.map { + "\($0.document.rawValue):\($0.line):\($0.column): related location" + } + return ([primary] + related).joined(separator: "\n") + }.joined(separator: "\n") + } + return String(describing: error) } static func updateFailureMessage(_ disposition: UpdateApplyDisposition, underlyingError: Error) @@ -154,7 +193,7 @@ enum Terminal { case .committed: outcome = "Update committed, but a later step failed." case .recoveryRequired: outcome = "Update failed; recovery is required." } - return outcome + "\n" + String(describing: underlyingError) + return outcome + "\n" + failureMessage(underlyingError) } static func updateFailureRemedy( @@ -308,12 +347,24 @@ enum Terminal { static func updateDifferences( _ report: CombinedUpdateReport, paths: HumanPaths ) { + let instructions = report.instructions + instructionNotes(instructions) if !report.hasChanges { - write("No changes.\n") + if instructions.conflicts.isEmpty { write("No changes.\n") } return } + for change in (report.marketplaceChanges ?? []).compactMap(PackagePinChange.init) { + write("Package \(line(change.name))\n") + if let before = change.before { + write( + " - \(line(before.package))@\(line(before.version)) \(line(before.archiveDigest))\n") + } + if let after = change.after { + write(" + \(line(after.package))@\(line(after.version)) \(line(after.archiveDigest))\n") + } + } + componentChanges(report.components, paths: paths, applied: false) let skills = report.skills - let instructions = report.instructions missingSkillLock(report.lockMissing && !skills.isEmpty) let items = HumanItem.ordered(skillItems(skills) + instructionItems(instructions)) for item in items { @@ -329,23 +380,33 @@ enum Terminal { skillFileDifferences(result, paths: paths) } } - instructionTargets(instructions.targets, paths: paths) + instructionTargets(instructions, paths: paths) for prompt in instructions.changedPrompts { write("Changed ChatGPT prompt \(line(prompt)).\n") } } static func instructionDifferences( _ report: InstructionUpdateReport, paths: HumanPaths = HumanPaths() ) { - if !report.hasChanges { write("No instruction changes.\n") } + instructionNotes(report) + if !report.hasChanges && report.conflicts.isEmpty { write("No instruction changes.\n") } for item in HumanItem.ordered(instructionItems(report)) { write(item.render(paths: paths)) } - instructionTargets(report.targets, paths: paths) + instructionTargets(report, paths: paths) for prompt in report.changedPrompts { write("Changed ChatGPT prompt \(line(prompt)).\n") } } - static func instructionTargets(_ targets: [InstructionTargetChange], paths: HumanPaths) { - for target in targets { + static func instructionNotes(_ report: InstructionUpdateReport) { + for conflict in report.conflicts { write("Conflict: \(line(conflict))\n") } + for advisory in report.advisories { write("\(line(advisory))\n") } + } + + static func instructionTargets( + _ report: InstructionUpdateReport, paths: HumanPaths, foreignOnly: Bool = false + ) { + for target in report.targets where !foreignOnly || target.foreign { let path = paths.path(target.url.path) - if target.foreign { write("Take over \(path), which agents did not generate\n") } + if target.foreign && report.conflicts.isEmpty { + write("Take over \(path), which agents did not generate\n") + } if target.agentsChanged { write( "Recipients of \(path): \(recipients(target.beforeAgents ?? [])) -> \(recipients(target.afterAgents))\n" @@ -371,7 +432,18 @@ enum Terminal { static func updatedInstructions(_ report: InstructionUpdateReport, paths: HumanPaths) { for target in report.targets where target.changed { - write("Updated \(paths.path(target.url.path)).\n") + instructionCompletion(target, paths: paths) + } + } + + static func instructionCompletion(_ target: InstructionTargetChange, paths: HumanPaths) { + let path = paths.path(target.url.path) + if target.after == nil { + write("Removed \(path).\n") + } else if target.before == nil { + write("Created \(path).\n") + } else { + write("Updated \(path).\n") } } diff --git a/Sources/CLI/WatchCommands.swift b/Sources/CLI/WatchCommands.swift index 548b710..b222f0d 100644 --- a/Sources/CLI/WatchCommands.swift +++ b/Sources/CLI/WatchCommands.swift @@ -26,26 +26,14 @@ struct AddWatch: ParsableCommand { @OptionGroup var requirements: RequirementOptions func run() throws { - let (id, seen) = try withRecovery { - let environment = RuntimeEnvironment() - let sources = try StateStore(scope: location.scope, environment: environment) - .loadDeclaration().sources - var input = source - if sources[source] == nil { - input = - try sources.keys.sorted().first { - try sources[$0]?.identity(environment: environment) == source - } ?? source - } - let id = try declaredSourceID(input, sources: sources, environment: environment) - let seen = try SkillOperations.watchOperations().add( - input, requirement: requirements.requirement, path: discovery.path, + let change = try withRecovery { + try SkillOperations.watchOperations().add( + source, requirement: requirements.requirement, path: discovery.path, scope: location.scope) - return (id, seen) } let suffix = - if case .revision(let revision) = seen { " from \(revision.prefix(7))" } else { "" } - Terminal.write("Watching \(location.paths.source(id))\(Terminal.line(suffix)).\n") + if case .revision(let revision) = change.seen { " from \(revision.prefix(7))" } else { "" } + Terminal.write("Watching \(location.paths.source(change.sourceID))\(Terminal.line(suffix)).\n") } } @@ -57,9 +45,7 @@ struct WatchStatusCommand: ParsableCommand { @Flag(help: "Print the versioned JSON report.") var json = false func run() throws { - let statuses = try withRecovery { - try SkillOperations.watchOperations().status(scope: location.scope) - } + let statuses = try SkillOperations.watchOperations().status(scope: location.scope) if json { try Terminal.json(WatchStatusReport(scope: location.scope.rawValue, statuses: statuses)) } else { @@ -80,10 +66,8 @@ struct DiffWatch: ParsableCommand { @Flag(help: "Print the versioned JSON report.") var json = false func run() throws { - let status = try withRecovery { - try SkillOperations.watchOperations().diff( - source, name: name, kind: kind, scope: location.scope) - } + let status = try SkillOperations.watchOperations().diff( + source, name: name, kind: kind, scope: location.scope) if json { try Terminal.json(WatchDiffReport(scope: location.scope.rawValue, status: status)) } else { @@ -101,17 +85,14 @@ struct SeenWatch: ParsableCommand { @OptionGroup var location: ScopeOptions func run() throws { - let (id, seen) = try withRecovery { - let environment = RuntimeEnvironment() - let declaration = try StateStore(scope: location.scope, environment: environment) - .loadDeclaration() - let id = try watchedSourceID(source, declaration: declaration, environment: environment) - let seen = try SkillOperations.watchOperations().seen( + let change = try withRecovery { + try SkillOperations.watchOperations().seen( source, revision: revision, scope: location.scope) - return (id, seen) } - let suffix = if case .revision(let revision) = seen { " at \(revision.prefix(7))" } else { "" } - Terminal.write("Marked \(location.paths.source(id)) seen\(Terminal.line(suffix)).\n") + let suffix = + if case .revision(let revision) = change.seen { " at \(revision.prefix(7))" } else { "" } + Terminal.write( + "Marked \(location.paths.source(change.sourceID)) seen\(Terminal.line(suffix)).\n") } } @@ -123,15 +104,11 @@ struct RemoveWatch: ParsableCommand { @OptionGroup var location: ScopeOptions func run() throws { - let id = try withRecovery { - let environment = RuntimeEnvironment() - let declaration = try StateStore(scope: location.scope, environment: environment) - .loadDeclaration() - let id = try watchedSourceID(source, declaration: declaration, environment: environment) + let change = try withRecovery { try SkillOperations.watchOperations().remove(source, scope: location.scope) - return id } - Terminal.write("Stopped watching \(location.paths.source(id)); installations are unchanged.\n") + Terminal.write( + "Stopped watching \(location.paths.source(change.sourceID)); installations are unchanged.\n") } } @@ -141,31 +118,3 @@ private func parseWatchKind(_ value: String) throws -> WatchItemKind { } return kind } - -// Mutations return a baseline or void. Confirmation identities follow core's -// subscribed-alias, subscribed-ID, then location precedence without fetching. -func watchedSourceID( - _ input: String, declaration: Declaration, environment: RuntimeEnvironment -) throws -> String { - let aliases = declaration.watch ?? [] - if !aliases.contains(input) { - for alias in aliases { - if try declaration.sources[alias]?.identity(environment: environment) == input { - return input - } - } - } - return try declaredSourceID(input, sources: declaration.sources, environment: environment) -} - -private func declaredSourceID( - _ input: String, sources: [String: SourceDeclaration], environment: RuntimeEnvironment -) throws -> String { - if let source = sources[input] { - return try source.identity(environment: environment) - } - return try SourceParser.identity( - for: SourceParser.parse( - input, currentDirectory: environment.projectDirectory, - homeDirectory: environment.homeDirectory)) -} diff --git a/Sources/CLI/WatchReports.swift b/Sources/CLI/WatchReports.swift index f242e70..1611336 100644 --- a/Sources/CLI/WatchReports.swift +++ b/Sources/CLI/WatchReports.swift @@ -29,7 +29,7 @@ struct WatchSourceReport: Encodable { let seen: WatchBaseline let current: WatchBaseline let commitCount: Int? - let changes: [WatchChange] + let changes: [WatchItemReport] init(_ status: WatchStatus, includeFiles: Bool) { alias = status.alias @@ -37,7 +37,7 @@ struct WatchSourceReport: Encodable { seen = WatchBaseline(status.seen) current = WatchBaseline(status.current) commitCount = status.commitCount - changes = status.changes.map { WatchChange($0, includeFiles: includeFiles) } + changes = status.changes.map { WatchItemReport($0, includeFiles: includeFiles) } } } @@ -57,7 +57,7 @@ struct WatchBaseline: Encodable { } } -struct WatchChange: Encodable { +struct WatchItemReport: Encodable { let name: String let kind: String let change: String diff --git a/Tests/CLITests/AuditExecutableTests.swift b/Tests/CLITests/AuditExecutableTests.swift new file mode 100644 index 0000000..84b08dd --- /dev/null +++ b/Tests/CLITests/AuditExecutableTests.swift @@ -0,0 +1,118 @@ +import Foundation +import Testing + +struct AuditExecutableTests { + @Test func scanReportsAndExitCodes() throws { + let cli = try CLIFixture() + let file = cli.project.appendingPathComponent("team notes.md") + let scan = ["audit", "--file", file.lastPathComponent] + let prompt = "fixture prompt text" + + try Data(prompt.utf8).write(to: file) + let clean = try cli.success(scan) + #expect(clean.stdout.contains("1 scanned, 0 skipped, 0 incomplete")) + + try Data((prompt + "\u{200B}").utf8).write(to: file) + let warning = try cli.run(scan + ["--format", "json"]) + #expect(warning.status == 2) + #expect(warning.stderr.isEmpty) + let json = try warning.json() + #expect(json["passesCI"] as? Bool == true) + #expect(json["ciExitCode"] as? Int == 0) + let findings = try #require(json["findings"] as? [[String: Any]]) + #expect(findings.map { $0["reason"] as? String } == ["zeroWidthCharacter"]) + #expect(!warning.stdout.contains(prompt)) + try cli.success(scan + ["--ci"]) + + try Data((prompt + "\u{202E}").utf8).write(to: file) + let critical = try cli.run(scan + ["--ci", "--format", "sarif"]) + #expect(critical.status == 1) + #expect(critical.stderr.isEmpty) + #expect(!critical.stdout.contains(prompt)) + let sarif = try critical.json() + #expect(sarif["version"] as? String == "2.1.0") + let runs = try #require(sarif["runs"] as? [[String: Any]]) + let run = try #require(runs.first) + #expect(run["columnKind"] as? String == "utf16CodeUnits") + let results = try #require(run["results"] as? [[String: Any]]) + let finding = try #require(results.first) + #expect(finding["level"] as? String == "error") + #expect(finding["ruleId"] as? String == "bidiControl") + let locations = try #require(finding["locations"] as? [[String: Any]]) + let physical = try #require(locations.first?["physicalLocation"] as? [String: Any]) + let artifact = try #require(physical["artifactLocation"] as? [String: Any]) + #expect(artifact["uri"] as? String == "team%20notes.md") + let region = try #require(physical["region"] as? [String: Int]) + #expect(region == ["startLine": 1, "startColumn": prompt.utf16.count + 1]) + } + + @Test func scopeDiscoveryReportsFilteredAndIncompleteCoverage() throws { + let cli = try CLIFixture() + let directory = cli.project.appendingPathComponent(".claude/commands") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try Data("Inspect\u{202E}\n".utf8).write(to: directory.appendingPathComponent("review.md")) + + let codex = try cli.success(["audit", "--agent", "codex"]) + #expect(codex.stdout.contains("0 scanned, 0 skipped, 0 incomplete")) + let claude = try cli.run(["audit", "--agent", "claude-code", "--ci"]) + #expect(claude.status == 1) + #expect(claude.stdout.contains(".claude/commands/review.md")) + let homeDirectory = cli.home.appendingPathComponent(".claude") + try FileManager.default.createDirectory(at: homeDirectory, withIntermediateDirectories: true) + try Data("Review project changes.\n".utf8).write( + to: homeDirectory.appendingPathComponent("CLAUDE.md")) + let user = try cli.success(["audit", "--scope", "user", "--agent", "claude-code"]) + #expect(user.stdout.contains("1 scanned, 0 skipped, 0 incomplete")) + + let skipped = try cli.success(["audit", "--file", "image.png"]) + #expect(skipped.stdout.contains("0 scanned, 1 skipped, 0 incomplete")) + let missing = try cli.run(["audit", "--file", "missing.md", "--ci"]) + #expect(missing.status == 1) + #expect(missing.stdout.contains("0 scanned, 0 skipped, 1 incomplete")) + #expect(missing.stdout.contains("missing.md")) + #expect(missing.stdout.contains("could not be read")) + #expect(!FileManager.default.fileExists(atPath: cli.state("agents.resolved").path)) + #expect(!FileManager.default.fileExists(atPath: cli.state(".agents.lock").path)) + } + + @Test func stripOnlyWritesWithExplicitApply() throws { + let cli = try CLIFixture() + let file = cli.project.appendingPathComponent("prompt.md") + let scan = ["audit", "--file", file.lastPathComponent] + let strip = scan + ["--strip"] + let before = Data("\u{FEFF}prompt text\u{202E}\r\n".utf8) + let after = Data("\u{FEFF}prompt text\r\n".utf8) + try before.write(to: file) + + let preview = try cli.success(strip) + #expect(preview.stdout.contains("U+202E")) + #expect(preview.stdout.contains("--apply")) + #expect(!preview.stdout.contains("prompt text")) + #expect(try Data(contentsOf: file) == before) + + let link = cli.project.appendingPathComponent("linked.md") + try FileManager.default.createSymbolicLink(at: link, withDestinationURL: file) + let refused = try cli.run(["audit", "--file", link.lastPathComponent, "--strip", "--apply"]) + #expect(refused.status == 1) + #expect(refused.stdout.isEmpty) + #expect(refused.stderr.contains("cannot be stripped")) + #expect(try Data(contentsOf: file) == before) + + for invalid in [ + scan + ["--apply"], ["audit", "--strip", "--apply"], + strip + ["--ci", "--apply"], strip + ["--format", "json", "--apply"], + strip + ["--agent", "codex", "--apply"], + ] { + let result = try cli.run(invalid) + #expect(result.status == 64) + #expect(result.stdout.isEmpty) + #expect(try Data(contentsOf: file) == before) + } + + let applied = try cli.success(strip + ["--apply"]) + #expect(applied.stdout.contains("Applied")) + #expect(!applied.stdout.contains("prompt text")) + #expect(try Data(contentsOf: file) == after) + try cli.success(scan) + } +} diff --git a/Tests/CLITests/AuthExecutableTests.swift b/Tests/CLITests/AuthExecutableTests.swift new file mode 100644 index 0000000..fc9e305 --- /dev/null +++ b/Tests/CLITests/AuthExecutableTests.swift @@ -0,0 +1,73 @@ +import Foundation +import Testing + +struct AuthExecutableTests { + @Test func scopedInspectionAndPipeOnlyExport() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + sources: + demo: {url: 'https://packages.example.invalid:8443/team/agents.git'} + """) + try fixture.writeManifest( + """ + version: 1 + sources: + demo: {path: '\(fixture.source.path)'} + """, scope: "user") + + let sourceResult = try fixture.run([ + "auth", "check", "--source", "demo@tag:release/v1", "--json", + ]) + #expect(sourceResult.status == 1) + let source = try sourceResult.json() + #expect(source["schemaVersion"] as? Int == 1) + #expect(source["scope"] as? String == "project") + #expect(source["provider"] == nil) + #expect(source["effectiveHost"] as? String == "packages.example.invalid:8443") + #expect(source["transport"] as? String == "https") + #expect(source["availability"] as? String == "unconfigured") + #expect(source["credentialSource"] == nil && source["validation"] == nil) + + try Data("version: 1\nallow: [local]\n".utf8).write(to: fixture.state("source-policy.yaml")) + let denied = try fixture.run(["auth", "check", "--source", "demo", "--json"]) + #expect(denied.status == 1 && denied.stdout.isEmpty) + #expect(denied.stderr.contains("project source policy: notAllowed")) + + let user = try fixture.success([ + "auth", "check", "--source", "demo", "--scope", "user", "--validate", "--json", + ]).json() + #expect(user["scope"] as? String == "user") + #expect(user["transport"] as? String == "local") + #expect(user["validation"] as? String == "indeterminate") + + let hostResult = try fixture.run([ + "auth", "check", "--host", "packages.example.invalid:8443", "--json", + ]) + #expect(hostResult.status == 1) + let host = try hostResult.json() + #expect(host["effectiveHost"] as? String == "packages.example.invalid:8443") + #expect(host["availability"] as? String == "unconfigured") + #expect(host["scope"] == nil && host["provider"] == nil && host["validation"] == nil) + + let provider = try fixture.run(["auth", "check", "--host", "GitHub.COM:443"]) + #expect(provider.status == 1) + #expect(provider.stdout.contains("Provider github\n")) + + for arguments in [ + ["check"], ["check", "--host", "github.com", "--source", "demo"], + ["check", "--host", "github.com", "--validate"], ["check", "--host", "github.com/fixture"], + ["check", "--host", "packages.example.invalid:"], + ["check", "--host", "packages.example.invalid:99999999999999999999999"], + ["export", "--source", "demo", "--json"], + ] { + let invalid = try fixture.run(["auth"] + arguments) + #expect(invalid.status == 64 && invalid.stdout.isEmpty) + } + + let export = try fixture.run(["auth", "export", "--scope", "user", "--source", "demo"]) + #expect(export.status == 1 && export.stdout.isEmpty) + #expect(export.stderr.contains("pipe-backed stdout")) + } +} diff --git a/Tests/CLITests/CLIFixture.swift b/Tests/CLITests/CLIFixture.swift index 6e59b49..56e3765 100644 --- a/Tests/CLITests/CLIFixture.swift +++ b/Tests/CLITests/CLIFixture.swift @@ -1,3 +1,5 @@ +import AgentsCore +import AgentsManifest import Foundation import Testing @@ -108,6 +110,37 @@ final class CLIFixture { .appendingPathComponent(name) } + func declaration(scope: String = "project") throws -> Declaration { + try StateStore( + scope: scope == "user" ? .user : .project, + environment: RuntimeEnvironment( + projectDirectory: project, homeDirectory: home, environment: environment) + ).loadDeclaration() + } + + func writeManifest(_ source: String, scope: String = "project") throws { + let url = state("agents.yaml", scope: scope) + try FileManager.default.createDirectory( + at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data((source + "\n").utf8).write(to: url) + } + + func declareSkills(mode: String = "link", agents: String = "[claude-code, codex]") throws { + try writeManifest( + """ + version: 1 + sources: + source: + path: \(source.path.debugDescription) + components: + - kind: skills + source: source + select: [pdf] + mode: \(mode) + agents: \(agents) + """) + } + private func process(_ executable: URL, _ arguments: [String], directory: URL) throws -> CLIResult { let stdout = root.appendingPathComponent("stdout") diff --git a/Tests/CLITests/CacheExecutableTests.swift b/Tests/CLITests/CacheExecutableTests.swift new file mode 100644 index 0000000..6f1ae93 --- /dev/null +++ b/Tests/CLITests/CacheExecutableTests.swift @@ -0,0 +1,32 @@ +import Foundation +import Testing + +struct CacheExecutableTests { + @Test func reportsEmptyCacheAndPreviewWithoutCreatingStorage() throws { + let fixture = try CLIFixture() + let info = try fixture.success(["cache", "info", "--json"]).json() + #expect(info["totalBytes"] as? Int == 0) + let stores = try #require(info["stores"] as? [[String: Any]]) + #expect(Set(stores.compactMap { $0["name"] as? String }) == ["git", "http", "deployed"]) + let path = try #require(info["root"] as? String) + let root = URL(fileURLWithPath: path).resolvingSymlinksInPath() + #expect(root.path.hasPrefix(fixture.home.resolvingSymlinksInPath().path + "/")) + let preview = try fixture.success(["cache", "prune", "--days", "7", "--json"]).json() + #expect(preview["days"] as? Int == 7) + #expect((preview["candidates"] as? [[String: Any]])?.isEmpty == true) + let applied = try fixture.success(["cache", "clean", "--apply", "--json"]).json() + #expect(applied["reclaimedBytes"] as? Int == 0) + #expect((applied["failures"] as? [[String: Any]])?.isEmpty == true) + #expect(!FileManager.default.fileExists(atPath: path)) + + let invalid = try fixture.run(["cache", "prune", "--days", "-1", "--apply"]) + #expect(invalid.status != 0) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let sentinel = root.appendingPathComponent("user-file.txt") + let bytes = Data("belongs to the user".utf8) + try bytes.write(to: sentinel) + let refused = try fixture.run(["cache", "clean", "--force"]) + #expect(refused.status != 0) + #expect(try Data(contentsOf: sentinel) == bytes) + } +} diff --git a/Tests/CLITests/ComponentExecutableTests.swift b/Tests/CLITests/ComponentExecutableTests.swift new file mode 100644 index 0000000..87c0beb --- /dev/null +++ b/Tests/CLITests/ComponentExecutableTests.swift @@ -0,0 +1,294 @@ +import AgentsCore +import ArgumentParser +import Foundation +import Testing + +@testable import CLI + +struct ComponentExecutableTests { + private func command(_ name: String = "review", body: String = "Review sources.") -> String { + """ + - kind: command + name: \(name) + description: Review + prompt: \(body.debugDescription) + agents: [claude-code] + """ + } + + @Test(arguments: ["project", "user"]) + func componentOnlyUpdateRestoreAndDoctor(_ scope: String) throws { + let fixture = try CLIFixture() + let args = ["--scope", scope] + try fixture.writeManifest( + "version: 1\n# Preserve this comment\ncomponents:\n" + command(), scope: scope) + let authored = try Data(contentsOf: fixture.state("agents.yaml", scope: scope)) + let preview = try fixture.success(["update", "--json"] + args).json() + let changes = try #require(preview["components"] as? [[String: Any]]) + #expect( + changes.contains { $0["kind"] as? String == "command" && $0["name"] as? String == "review" }) + #expect(preview["schemaVersion"] as? Int == 2 && preview["changed"] as? Bool == true) + #expect(try Data(contentsOf: fixture.state("agents.yaml", scope: scope)) == authored) + try fixture.success(["update", "--apply"] + args) + let listed = try fixture.success(["components", "list", "--json"] + args).json() + #expect((listed["components"] as? [[String: Any]])?.count == 1) + let inventory = try fixture.success(["components", "inventory"] + args).json() + #expect(inventory["bomFormat"] as? String == "CycloneDX") + #expect(inventory["specVersion"] as? String == "1.6") + let packages = try #require(inventory["components"] as? [[String: Any]]) + let members = packages.flatMap { $0["components"] as? [[String: Any]] ?? [] } + let member = try #require(members.first { $0["name"] as? String == "review" }) + let properties = try #require(member["properties"] as? [[String: String]]) + #expect(properties.contains(["name": "agents:kind", "value": "command"])) + #expect(properties.contains(["name": "agents:target", "value": "claude-code"])) + let diagnosis = try fixture.run(["doctor", "--json"] + args) + #expect(diagnosis.status == 0 && diagnosis.stderr.isEmpty) + let doctor = try diagnosis.json() + let roots = try #require(doctor["roots"] as? [[String: Any]]) + let checks = try #require(roots.first?["checks"] as? [[String: Any]]) + let target = try #require( + checks.first { $0["kind"] as? String == "components" }?["path"] as? String) + try FileManager.default.removeItem(atPath: target) + let broken = try fixture.run(["doctor", "--json"] + args) + #expect(broken.status == 1) + #expect(!FileManager.default.fileExists(atPath: target)) + let restored = try fixture.success(["install", "--json"] + args).json() + #expect(restored["schemaVersion"] as? Int == 2) + #expect((restored["components"] as? [[String: Any]])?.isEmpty == false) + #expect(FileManager.default.fileExists(atPath: target)) + #expect(try Data(contentsOf: fixture.state("agents.yaml", scope: scope)) == authored) + let noOp = try fixture.success(["update", "--json"] + args).json() + #expect(noOp["changed"] as? Bool == false) + try fixture.success(["components", "remove", "review"] + args) + #expect( + try String(contentsOf: fixture.state("agents.yaml", scope: scope), encoding: .utf8).contains( + "# Preserve this comment")) + } + + @Test func inventoryPreservesSelectedVersionAndSourceRevision() throws { + let fixture = try CLIFixture() + try fixture.skill("review", body: "Private inventory fixture content.") + try fixture.commit() + try fixture.git(["tag", "1.2.3"]) + let revision = try fixture.git(["rev-parse", "HEAD"]).stdout.trimmingCharacters( + in: .whitespacesAndNewlines) + try fixture.success([ + "skills", "add", fixture.source.path, "review", "--exact", "1.2.3", "--agent", "codex", + ]) + + let inventory = try fixture.success(["components", "inventory"]) + let packages = try #require(try inventory.json()["components"] as? [[String: Any]]) + let package = try #require( + packages.first { package in + (package["components"] as? [[String: Any]])?.contains { $0["name"] as? String == "review" } + == true + }) + let members = try #require(package["components"] as? [[String: Any]]) + let review = try #require(members.first { $0["name"] as? String == "review" }) + #expect(review["version"] as? String == "1.2.3") + let properties = try #require(package["properties"] as? [[String: String]]) + #expect(properties.contains(["name": "agents:revision", "value": revision])) + #expect(!inventory.stdout.contains("Private inventory fixture content.")) + #expect(!inventory.stdout.contains(fixture.root.path)) + } + + @Test func discoveryIsReadOnlyAndAddUsesCoreGroupIntent() throws { + let fixture = try CLIFixture() + try FileManager.default.createDirectory( + at: fixture.source.appendingPathComponent(".agent"), withIntermediateDirectories: true) + let producer = + "version: 1\ngroups:\n tools:\n components:\n" + + command().split(separator: "\n").map { " " + $0 }.joined(separator: "\n") + + "\nexports: [tools]\n" + try Data(producer.utf8).write(to: fixture.source.appendingPathComponent(".agent/agents.yaml")) + let selection = [fixture.source.path, "--alias", "tools", "--group", "tools"] + let listed = try fixture.success(["components", "list"] + selection + ["--json"]).json() + #expect((listed["components"] as? [[String: Any]])?.first?["name"] as? String == "review") + #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.yaml").path)) + try fixture.success(["components", "add"] + selection) + #expect(try fixture.declaration().uses.contains { $0.name == "tools" && $0.source == "tools" }) + let before = try Data(contentsOf: fixture.state("agents.yaml")) + let refused = try fixture.run(["components", "remove", "review"]) + #expect(refused.status == 1 && refused.stderr.contains("notEditableHere")) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == before) + } + + @Test func missingAndPendingInspectionDoesNotCreateOrRecoverState() throws { + let fixture = try CLIFixture() + try fixture.success(["components", "list", "--json"]) + #expect(!FileManager.default.fileExists(atPath: fixture.state("").path)) + try fixture.writeManifest("version: 1") + let pending = fixture.state("transaction.new") + try Data("pending".utf8).write(to: pending) + let before = try Data(contentsOf: pending) + for command in [ + ["components", "list"], ["components", "inventory"], ["mcp", "test", "server"], + ] { + let result = try fixture.run(command) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect(try Data(contentsOf: pending) == before) + } + } + + @Test func exactSelectionRefusesDuplicateNamesAndUsesIdentity() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + components: + - kind: command + name: same + description: Command + prompt: Review + agents: [claude-code] + - kind: subagent + name: same + description: Agent + prompt: Research + agents: [codex] + """) + try fixture.success(["update", "--apply"]) + let before = try Data(contentsOf: fixture.state("agents.yaml")) + let ambiguous = try fixture.run(["components", "remove", "same"]) + #expect(ambiguous.status == 1 && ambiguous.stderr.contains("ambiguous")) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == before) + let report = try fixture.success(["components", "list", "--json"]).json() + let items = try #require(report["components"] as? [[String: Any]]) + let selected = try #require(items.first { $0["kind"] as? String == "command" }) + let identity = try #require(selected["identity"] as? String) + let occurrences = try #require(selected["occurrences"] as? [[String: Any]]) + let occurrence = try #require(occurrences.first?["id"] as? Int) + try fixture.success([ + "components", "remove", "same", "--identity", identity, "--occurrence", String(occurrence), + ]) + #expect(try fixture.declaration().components.contains { $0.kind == .subagent }) + } + + @Test func importPreviewIsReadOnlyAndApplyKeepsAuthoredComments() throws { + let fixture = try CLIFixture() + try fixture.writeManifest("version: 1\n# Authored intent") + let input = fixture.source.appendingPathComponent("review.md") + try Data("---\ndescription: Review changes\n---\nReview exact changes.\n".utf8).write(to: input) + let args = [ + "import", "review.md", "--root", fixture.source.path, "--format", "claudeCommandV1", + ] + let authored = try Data(contentsOf: fixture.state("agents.yaml")) + let preview = try fixture.success(args + ["--json"]).json() + #expect(preview["kind"] as? String == "import") + #expect((preview["components"] as? [[String: Any]])?.count == 1) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == authored) + try Data("---\ndescription: Review changes\n---\nReview newly saved changes.\n".utf8).write( + to: input) + try fixture.success(args + ["--apply"]) + #expect( + try String(contentsOf: fixture.state("agents.yaml"), encoding: .utf8).contains( + "# Authored intent")) + let diagnosis = try fixture.run(["doctor", "--json"]) + #expect(diagnosis.status == 0 && diagnosis.stderr.isEmpty) + let roots = try #require(try diagnosis.json()["roots"] as? [[String: Any]]) + let checks = try #require(roots.first?["checks"] as? [[String: Any]]) + let target = try #require( + checks.first { $0["kind"] as? String == "components" }?["path"] as? String) + #expect( + try String(contentsOfFile: target, encoding: .utf8).contains("Review newly saved changes.")) + } + + @Test func runtimePreviewDoesNotRequestBindingsAndMCPRequiresExplicitMapping() throws { + let fixture = try CLIFixture() + let authored = """ + version: 1 + components: + - kind: mcpServer + name: selected + agents: [] + transport: + kind: stdio + executable: never-start-without-a-binding + environment: {TOKEN: {secret: selected-token}} + """ + try fixture.writeManifest( + authored.replacingOccurrences(of: "agents: []", with: "agents: [codex]")) + let preview = try fixture.success([ + "update", "--json", "--binding", "selected-token=MISSING_VALUE", + ]) + #expect(!preview.stdout.contains("runtime binding unavailable")) + #expect(preview.stdout.contains("selected-token")) + try fixture.writeManifest(authored) + try fixture.success(["update", "--apply"]) + let before = try Data(contentsOf: fixture.state("agents.resolved")) + let result = try fixture.run(["mcp", "test", "selected"]) + #expect(result.status == 1) + #expect(result.stderr.contains("runtime binding unavailable: selected-token")) + #expect(try Data(contentsOf: fixture.state("agents.resolved")) == before) + } + + @Test func restoreFailureDoesNotPublishPartialSkillSuccess() throws { + let fixture = try CLIFixture() + try fixture.skill() + try fixture.commit() + try fixture.success([ + "skills", "add", fixture.source.path, "--mode", "copy", "--agent", "codex", + ]) + try fixture.writeManifest( + "version: 1\nsources:\n source: {path: \(fixture.source.path.debugDescription)}\ncomponents:\n- kind: skills\n source: source\n select: [demo]\n mode: copy\n agents: [codex]\n" + + command()) + try fixture.success(["update", "--apply"]) + let skills = try fixture.success(["skills", "list", "--json"]).json() + let rows = try #require(skills["skills"] as? [[String: Any]]) + let path = try #require(rows.first?["path"] as? String) + let diagnosis = try fixture.run(["doctor", "--json"]) + #expect(diagnosis.status == 0 && diagnosis.stderr.isEmpty) + let roots = try #require(try diagnosis.json()["roots"] as? [[String: Any]]) + let checks = try #require(roots.first?["checks"] as? [[String: Any]]) + let native = try #require( + checks.first { $0["kind"] as? String == "components" }?["path"] as? String) + try FileManager.default.removeItem(atPath: path) + let commands = URL(fileURLWithPath: native).deletingLastPathComponent() + try FileManager.default.removeItem(at: commands) + try Data("retained conflicting parent".utf8).write(to: commands) + let result = try fixture.run(["install"]) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect(!FileManager.default.fileExists(atPath: path)) + #expect(try String(contentsOf: commands, encoding: .utf8) == "retained conflicting parent") + } + + @Test func failedMCPConnectionReportsCleanupWithoutChangingState() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + components: + - kind: mcpServer + name: unavailable + agents: [] + transport: + kind: stdio + executable: agents-owned-missing-fixture + """) + try fixture.success(["update", "--apply"]) + let before = try Data(contentsOf: fixture.state("agents.resolved")) + let result = try fixture.run(["mcp", "test", "unavailable", "--json"]) + #expect(result.status == 1 && result.stderr.isEmpty) + let report = try result.json() + #expect(report["kind"] as? String == "mcp-test" && report["schemaVersion"] as? Int == 1) + #expect(report["outcome"] as? String == "failed") + #expect(report["cleanupComplete"] as? Bool == true) + #expect((report["tools"] as? [[String: Any]])?.isEmpty == true) + #expect(try Data(contentsOf: fixture.state("agents.resolved")) == before) + } + + @Test func bindingMappingIsExplicitLazyAndBounded() throws { + let options = try BindingOptions.parse(["--binding", "token=EXPLICIT_VALUE"]) + let provider = try options.provider() + let runtime = RuntimeEnvironment(environment: [ + "EXPLICIT_VALUE": "private-canary", "OTHER": "unrelated", + ]) + #expect(try provider.value(for: "token", environment: runtime) == Data("private-canary".utf8)) + #expect(throws: CoreError.invalidState("runtime binding unavailable: other")) { + try provider.value(for: "other", environment: runtime) + } + #expect(throws: (any Error).self) { + try BindingOptions.parse(["--binding", "token=A", "--binding", "token=B"]) + } + } +} diff --git a/Tests/CLITests/ExecutableTests.swift b/Tests/CLITests/ExecutableTests.swift index 469cd20..693b258 100644 --- a/Tests/CLITests/ExecutableTests.swift +++ b/Tests/CLITests/ExecutableTests.swift @@ -32,7 +32,7 @@ struct ExecutableTests { #expect(humanList.contains(displayPath)) #expect(!humanList.contains(installed.path)) let lock = try Data(contentsOf: fixture.state("agents.resolved", scope: scope)) - let declaration = try Data(contentsOf: fixture.state("agents.json", scope: scope)) + let declaration = try Data(contentsOf: fixture.state("agents.yaml", scope: scope)) try FileManager.default.removeItem(at: installed) let missing = try fixture.success(["doctor", "--json"] + scopeArguments).json() let roots = try #require(missing["roots"] as? [[String: Any]]) @@ -50,7 +50,7 @@ struct ExecutableTests { let preview = try fixture.success(["update", "--json"] + scopeArguments).json() #expect( Set(preview.keys) == [ - "schemaVersion", "scope", "changed", "skills", "instructions", "lockMissing", + "schemaVersion", "scope", "changed", "skills", "instructions", "lockMissing", "components", ]) #expect(preview["schemaVersion"] as? Int == 2 && preview["changed"] as? Bool == true) let updates = try #require(preview["skills"] as? [[String: Any]]) @@ -72,7 +72,7 @@ struct ExecutableTests { #expect(Data(base64Encoded: try #require(before["base64"] as? String)) == original) #expect(try Data(contentsOf: file) == original) #expect(try Data(contentsOf: fixture.state("agents.resolved", scope: scope)) == lock) - #expect(try Data(contentsOf: fixture.state("agents.json", scope: scope)) == declaration) + #expect(try Data(contentsOf: fixture.state("agents.yaml", scope: scope)) == declaration) let applied = try fixture.success(["update", "--apply"] + scopeArguments) let diffIndex = try #require(applied.stdout.range(of: "+Updated upstream content")?.lowerBound) let appliedIndex = try #require(applied.stdout.range(of: "Updated ")?.lowerBound) @@ -95,7 +95,7 @@ struct ExecutableTests { let available = try fixture.success(["skills", "add", fixture.source.path]) #expect(available.stdout.contains("one") && available.stdout.contains("two")) #expect(available.stdout.contains("--all")) - #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.json").path)) + #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.yaml").path)) let list = try fixture.success([ "skills", "list", fixture.source.path, "--full-depth", "--path", "skills", "--json", ]).json() @@ -157,7 +157,7 @@ struct ExecutableTests { #expect(root["scope"] as? String == "project") #expect((root["checks"] as? [Any])?.isEmpty == true) } - #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.json").path)) + #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.yaml").path)) #expect( !FileManager.default.fileExists(atPath: fixture.project.appendingPathComponent(".agent").path) ) @@ -191,20 +191,21 @@ struct ExecutableTests { #expect(existing.status == 1 && existing.stderr.contains("already exists")) } - @Test(arguments: ["project", "user"], ["transaction.json", "transaction.new"]) - func doctorLeavesPendingRecoveryUnchanged(scope: String, journal: String) throws { + @Test(arguments: ["project", "user"]) + func doctorLeavesPendingRecoveryUnchanged(_ scope: String) throws { let fixture = try CLIFixture() let state = fixture.state("", scope: scope) let cache = fixture.state("cache/content", scope: scope) try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: true) let files = [ - fixture.state(journal, scope: scope), fixture.state("agents.json", scope: scope), + fixture.state("transaction.new", scope: scope), fixture.state("agents.yaml", scope: scope), fixture.state("agents.resolved", scope: scope), cache.appendingPathComponent("snapshot"), ] for (file, content) in zip( files, [ - Data("{}".utf8), Data("incomplete declaration".utf8), Data("incomplete lock".utf8), + Data("partial journal".utf8), Data("incomplete declaration".utf8), + Data("incomplete lock".utf8), Data([0, 255]), ]) { @@ -226,10 +227,13 @@ struct ExecutableTests { let roots = try #require(report["roots"] as? [[String: Any]]) #expect(roots.count == 1 && roots.first?["ok"] as? Bool == false) let checks = try #require(roots.first?["checks"] as? [[String: Any]]) - #expect(checks.count == 2) - #expect(checks.compactMap { $0["kind"] as? String } == ["skills", "instructions"]) + #expect(checks.count == 3) #expect( - checks.compactMap { $0["id"] as? String } == ["pending-recovery", "pendingRecovery"]) + checks.compactMap { $0["kind"] as? String } == ["skills", "instructions", "components"]) + #expect( + checks.compactMap { $0["id"] as? String } == [ + "pending-recovery", "pendingRecovery", "pending-recovery", + ]) for check in checks { #expect(Set(check.keys) == ["kind", "id", "status", "message", "path"]) #expect(check["status"] as? String == "error") @@ -251,8 +255,8 @@ struct ExecutableTests { let fixture = try CLIFixture() let state = fixture.state("", scope: "user") try FileManager.default.createDirectory(at: state, withIntermediateDirectories: true) - let journal = fixture.state("transaction.json", scope: "user") - try Data("{}".utf8).write(to: journal) + let journal = fixture.state("transaction.new", scope: "user") + try Data("partial journal".utf8).write(to: journal) let message = "Transaction recovery is pending; run 'agents install --scope user' to finish recovery." let human = try fixture.run(["doctor", "--root", fixture.source.path]) @@ -273,7 +277,7 @@ struct ExecutableTests { "message": message, "path": state.path, ] ]) - #expect(try Data(contentsOf: journal) == Data("{}".utf8)) + #expect(try Data(contentsOf: journal) == Data("partial journal".utf8)) } @Test func previewDescribesEntryTypesAndDeletions() throws { @@ -398,7 +402,7 @@ struct ExecutableTests { let result = try fixture.success(["--help"]) #expect( result.stdout.contains( - "OVERVIEW: Manage agent skills and instructions from declared sources.")) + "OVERVIEW: Manage agent components from declared sources.")) #expect( result.stdout.contains( """ @@ -423,11 +427,11 @@ struct ExecutableTests { ), ( [["skills", "add"]], - "Agent to install for: codex, claude-code, cursor, gemini-cli or opencode. Repeat for several. Default: the agents already recorded for this skill or source, else the declaration's agents, else codex and claude-code." + "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", "list"], ["skills", "remove"], ["doctor"]], - "Limit to this agent: codex, claude-code, cursor, gemini-cli or opencode. Repeat for several. Default: all recipients." + "Limit to this agent: codex, claude-code, cursor, gemini-cli, opencode, or antigravity. Repeat for several. Default: all recipients." ), ( [["skills", "add"]], diff --git a/Tests/CLITests/HumanExecutableTests.swift b/Tests/CLITests/HumanExecutableTests.swift index 245e6c9..5c242ad 100644 --- a/Tests/CLITests/HumanExecutableTests.swift +++ b/Tests/CLITests/HumanExecutableTests.swift @@ -7,12 +7,13 @@ struct HumanExecutableTests { @Test func missingGitSourceHasConciseFailureAndRemedy() throws { let fixture = try CLIFixture() let source = "file://localhost" + fixture.home.appendingPathComponent("missing.git").path - try FileManager.default.createDirectory( - at: fixture.state("agents.json").deletingLastPathComponent(), - withIntermediateDirectories: true) - try JSONSerialization.data(withJSONObject: [ - "sources": ["missing": ["git": source]] - ]).write(to: fixture.state("agents.json")) + try fixture.writeManifest( + """ + version: 1 + sources: + missing: + url: \(source.debugDescription) + """) let failure = try fixture.run(["skills", "add", "missing", "demo"]) #expect(failure.status == 1 && failure.stdout.isEmpty) #expect(failure.stderr.hasPrefix("Error: Git could not clone \(source).\n")) @@ -25,14 +26,21 @@ struct HumanExecutableTests { try fixture.skill() try fixture.commit() try fixture.success(["skills", "add", fixture.source.path, "demo"]) + let declaration = try Data(contentsOf: fixture.state("agents.yaml")) + let lock = try Data(contentsOf: fixture.state("agents.resolved")) + let target = fixture.project.appendingPathComponent(".agents/skills/demo/SKILL.md") + let installed = try Data(contentsOf: target) try FileManager.default.removeItem(at: fixture.source.appendingPathComponent(".git")) let failure = try fixture.run(["skills", "update"]) #expect(failure.status == 1 && failure.stdout.isEmpty) - #expect(failure.stderr.hasPrefix("Error: Git could not fetch \(fixture.source.path).\n")) - #expect(failure.stderr.contains("\n fatal: Could not read from remote repository.\n")) + #expect(failure.stderr.hasPrefix("Error: ")) #expect( - failure.stderr.hasSuffix( - " and the repository exists.\n Check Git access and the source location.\n")) + failure.stderr.contains("Git could not ") && failure.stderr.contains(fixture.source.path)) + #expect(failure.stderr.contains("fatal:")) + #expect(failure.stderr.hasSuffix("\n Check Git access and the source location.\n")) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == declaration) + #expect(try Data(contentsOf: fixture.state("agents.resolved")) == lock) + #expect(try Data(contentsOf: target) == installed) let lines = failure.stderr.split(separator: "\n", omittingEmptySubsequences: false) #expect(lines.dropFirst().dropLast().allSatisfy { $0.hasPrefix(" ") }) #expect(!failure.stderr.contains("\\n") && !failure.stderr.contains("\n .")) @@ -76,7 +84,7 @@ struct HumanExecutableTests { #expect(applied.hasSuffix("Updated AGENTS.md.\n")) let removed = try fixture.success(["instructions", "remove", "commits"]).stdout #expect(removed.contains("--- a/AGENTS.md\n+++ b/AGENTS.md\n@@")) - #expect(removed.hasSuffix("Removed commits from AGENTS.md.\n")) + #expect(removed.hasSuffix("Updated AGENTS.md.\n")) } @Test func topLevelInstructionChangesWithUnchangedSkills() throws { @@ -200,18 +208,27 @@ struct HumanExecutableTests { try fixture.success([ "skills", "add", fixture.source.path, "pdf", "--mode", "edit", "--agent", "codex", ]) - var declaration = try fixture.declaration() - var skills = try #require(declaration["skills"] as? [String: [String: Any]]) - let alias = try #require(skills.keys.first) - skills[alias]?["agents"] = ["cursor"] - declaration["skills"] = skills - try JSONSerialization.data(withJSONObject: declaration).write(to: fixture.state("agents.json")) + try fixture.declareSkills(mode: "edit", agents: "[cursor]") let preview = try fixture.success(["skills", "update"]).stdout #expect(preview.hasPrefix("~ changed pdf ")) try Data("# Claude Guide\n\nCustom notes.\n".utf8).write( to: fixture.project.appendingPathComponent("CLAUDE.md")) - let added = try fixture.success(["instructions", "add", fixture.source.path]).stdout - #expect(added == "Added canonical-artifacts to AGENTS.md (claude-code, codex).\n") + let declaration = try Data(contentsOf: fixture.state("agents.yaml")) + let lock = try Data(contentsOf: fixture.state("agents.resolved")) + let claude = fixture.project.appendingPathComponent("CLAUDE.md") + let notes = try Data(contentsOf: claude) + let skill = fixture.project.appendingPathComponent(".agents/skills/pdf") + let destination = try FileManager.default.destinationOfSymbolicLink(atPath: skill.path) + let refused = try fixture.run(["instructions", "add", fixture.source.path]) + #expect(refused.status == 1 && refused.stdout.isEmpty) + #expect(refused.stderr.contains("requiresCombinedUpdate") && refused.stderr.contains("pdf")) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == declaration) + #expect(try Data(contentsOf: fixture.state("agents.resolved")) == lock) + #expect(try Data(contentsOf: claude) == notes) + #expect(try FileManager.default.destinationOfSymbolicLink(atPath: skill.path) == destination) + #expect( + !FileManager.default.fileExists( + atPath: fixture.project.appendingPathComponent("AGENTS.md").path)) } @Test func promptErrorsAndUsagePunctuation() throws { @@ -220,7 +237,7 @@ struct HumanExecutableTests { #expect(missing.status == 1 && missing.stdout.isEmpty) #expect( missing.stderr - == "Error: No ChatGPT prompt named 'daily' is declared.\n Declare it under instructions.chatgpt in agents.json and run 'agents instructions update --apply'.\n" + == "Error: No ChatGPT prompt named 'daily' is declared.\n Declare it under chatgpt in the instructions component of agents.yaml and run 'agents instructions update --apply'.\n" ) #expect(!FileManager.default.fileExists(atPath: fixture.state("").path)) try fixture.instruction() @@ -237,7 +254,7 @@ struct HumanExecutableTests { #expect(unlocked.status == 1) #expect( unlocked.stderr - == "Error: A ChatGPT prompt must have at least one locked section.\n Declare the ChatGPT prompt in agents.json and run 'agents instructions update --apply'.\n" + == "Error: A ChatGPT prompt must have at least one locked section.\n Declare the ChatGPT prompt in agents.yaml and run 'agents instructions update --apply'.\n" ) let journal = fixture.state("transaction.new") try Data("pending".utf8).write(to: journal) diff --git a/Tests/CLITests/InstructionExecutableTests.swift b/Tests/CLITests/InstructionExecutableTests.swift index c3c5be1..9d6b12d 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -1,10 +1,141 @@ +import AgentsCore import AgentsInstructions +import AgentsManifest import Foundation import Testing @testable import CLI struct InstructionExecutableTests { + @Test func antigravityRulesUseIndependentSectionsAndSharedLifecycleReports() throws { + let fixture = try CLIFixture() + try fixture.instruction("review", heading: "Review", body: "Review changes.") + try fixture.instruction("commits", heading: "Commits", body: "Write clear commit messages.") + try fixture.instruction("legacy", heading: "Legacy", body: "Keep the legacy instructions.") + try fixture.commit() + let scope = ["--scope", "user"] + try fixture.writeManifest( + """ + version: 1 + sources: + team: {path: \(fixture.source.path.debugDescription)} + components: + - kind: instructions + agents: [codex, gemini-cli] + sections: + - {source: team, name: legacy} + """, scope: "user") + try fixture.success(["instructions", "update", "--apply"] + scope) + let codex = fixture.home.appendingPathComponent(".codex/AGENTS.md") + let gemini = fixture.home.appendingPathComponent(".gemini/GEMINI.md") + let codexBefore = try Data(contentsOf: codex) + let geminiBefore = try Data(contentsOf: gemini) + + let add = + ["instructions", "add", "team", "review", "commits", "--agent", "antigravity"] + + scope + let added = try fixture.success(add).stdout + let rules = fixture.home.appendingPathComponent(".gemini/config/rules") + let files = try FileManager.default.contentsOfDirectory( + at: rules, includingPropertiesForKeys: nil) + #expect(files.count == 2) + let review = try #require( + try files.first { + try String(contentsOf: $0, encoding: .utf8).contains("Review changes.") + }) + let commits = try #require(files.first { $0 != review }) + let reviewBytes = try Data(contentsOf: review) + let commitsBytes = try Data(contentsOf: commits) + #expect(String(decoding: reviewBytes, as: UTF8.self).contains("trigger: always_on")) + #expect(!String(decoding: reviewBytes, as: UTF8.self).contains("Write clear commit messages.")) + #expect(String(decoding: commitsBytes, as: UTF8.self).contains("Write clear commit messages.")) + #expect(added.contains("Added review to ~/.gemini/config/rules/\(review.lastPathComponent)")) + #expect(added.contains("Added commits to ~/.gemini/config/rules/\(commits.lastPathComponent)")) + #expect(try Data(contentsOf: codex) == codexBefore) + #expect(try Data(contentsOf: gemini) == geminiBefore) + + let manifest = fixture.state("agents.yaml", scope: "user") + let declaration = try Data(contentsOf: manifest) + try fixture.success(add) + #expect(try Data(contentsOf: manifest) == declaration) + let preview = try fixture.success(["instructions", "update", "--json"] + scope).json() + let previewChanges = try #require(preview["instructions"] as? [String: Any]) + let advisory = try #require((previewChanges["advisories"] as? [String])?.first) + #expect(advisory.contains("20,000-token budget")) + #expect(preview["changed"] as? Bool == false) + #expect(try fixture.success(["update"] + scope).stdout.contains(advisory)) + + let reviewDirectory = review.deletingLastPathComponent().resolvingSymlinksInPath().path + func isReviewPath(_ value: Any?) -> Bool { + guard let path = value as? String, path.hasPrefix("/") else { return false } + let file = URL(fileURLWithPath: path) + // The parent still exists when doctor reports the missing rule. + return file.lastPathComponent == review.lastPathComponent + && file.deletingLastPathComponent().resolvingSymlinksInPath().path == reviewDirectory + } + + try FileManager.default.removeItem(at: review) + let doctor = try fixture.success(["doctor", "--json"] + scope).json() + let firstRoot = try #require((doctor["roots"] as? [[String: Any]])?.first) + let checks = try #require(firstRoot["checks"] as? [[String: Any]]) + #expect( + checks.contains { + $0["kind"] as? String == "instructions" + && $0["id"] as? String == "missingTarget" && isReviewPath($0["path"]) + }) + + let install = try fixture.success(["install", "--json"] + scope).json() + let instructions = try #require(install["instructions"] as? [String: Any]) + let targets = try #require(instructions["targets"] as? [[String: Any]]) + #expect( + targets.contains { + isReviewPath($0["path"]) + && $0["target"] as? String == "~/.gemini/config/rules/\(review.lastPathComponent)" + && $0["afterAgents"] as? [String] == ["antigravity"] && $0["changed"] as? Bool == true + && $0["drift"] as? String == "missing" + }) + #expect(try Data(contentsOf: review) == reviewBytes) + #expect(try Data(contentsOf: commits) == commitsBytes) + + let unmanaged = Data("---\ntrigger: always_on\n---\n# Hand-written\n".utf8) + try unmanaged.write(to: review) + let blocked = try fixture.success(["instructions", "update", "--json"] + scope).json() + let blockedChanges = try #require(blocked["instructions"] as? [String: Any]) + let conflict = try #require((blockedChanges["conflicts"] as? [String])?.first) + #expect(conflict.contains(review.lastPathComponent)) + let blockedPreview = try fixture.success(["instructions", "update"] + scope).stdout + #expect(blockedPreview.contains(conflict)) + #expect(!blockedPreview.contains("Run again with --apply")) + let apply = try fixture.run(["instructions", "update", "--apply", "--replace"] + scope) + #expect(apply.status == 1 && apply.stderr.contains(conflict)) + #expect(try Data(contentsOf: review) == unmanaged) + try reviewBytes.write(to: review) + + let removed = try fixture.success(["instructions", "remove", "review"] + scope).stdout + #expect(removed.contains("Removed ~/.gemini/config/rules/\(review.lastPathComponent).")) + #expect(!FileManager.default.fileExists(atPath: review.path)) + #expect(try Data(contentsOf: commits) == commitsBytes) + #expect(try Data(contentsOf: codex) == codexBefore) + #expect(try Data(contentsOf: gemini) == geminiBefore) + } + + @Test func oversizedAntigravityRuleReportsTheRuleAndLeavesStateUntouched() throws { + let fixture = try CLIFixture() + try fixture.instruction("large", heading: "Large", body: String(repeating: "界", count: 8_001)) + try fixture.commit() + let result = try fixture.run([ + "instructions", "add", fixture.source.path, "large", "--scope", "user", "--agent", + "antigravity", + ]) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect(result.stderr.contains("large") && result.stderr.contains("24000")) + #expect(result.stderr.contains("UTF-8 bytes")) + #expect( + !FileManager.default.fileExists(atPath: fixture.state("agents.yaml", scope: "user").path)) + #expect( + !FileManager.default.fileExists(atPath: fixture.state("agents.resolved", scope: "user").path)) + } + @Test(arguments: ["project", "user"]) func lifecycle(_ scope: String) throws { let fixture = try CLIFixture() @@ -41,7 +172,7 @@ struct InstructionExecutableTests { try fixture.instruction(body: "Updated instructions") try fixture.commit() try fixture.declarePrompt(scope: scope) - let declaration = try Data(contentsOf: fixture.state("agents.json", scope: scope)) + let declaration = try Data(contentsOf: fixture.state("agents.yaml", scope: scope)) let lock = try Data(contentsOf: fixture.state("agents.resolved", scope: scope)) let preview = try fixture.success(["instructions", "update"] + arguments) #expect( @@ -57,7 +188,7 @@ struct InstructionExecutableTests { #expect(Data(base64Encoded: try #require(before["base64"])) == Data(drift.utf8)) #expect(files.first?["drift"] as? String == "drifted") #expect(files.first?["foreign"] as? Bool == false) - #expect(try Data(contentsOf: fixture.state("agents.json", scope: scope)) == declaration) + #expect(try Data(contentsOf: fixture.state("agents.yaml", scope: scope)) == declaration) #expect(try Data(contentsOf: fixture.state("agents.resolved", scope: scope)) == lock) #expect(try Data(contentsOf: target) == Data(drift.utf8)) let applied = try fixture.success(["instructions", "update", "--apply"] + arguments) @@ -101,7 +232,7 @@ struct InstructionExecutableTests { let choices = try fixture.success(["instructions", "add"] + sourceArguments) #expect(choices.stdout.contains("canonical-artifacts") && choices.stdout.contains("other")) #expect(choices.stdout.contains("Canonical Artifacts rules.")) - #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.json").path)) + #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.yaml").path)) let discovered = try fixture.success(["instructions", "list"] + sourceArguments + ["--json"]) .json() #expect(discovered["kind"] as? String == "source") @@ -131,9 +262,8 @@ struct InstructionExecutableTests { #expect(replaced.stdout.contains("+Original instructions")) try fixture.success(["instructions", "add", "source", "other"]) let declaration = try fixture.declaration() - let instructions = try #require(declaration["instructions"] as? [String: Any]) #expect( - instructions["sections"] as? [String] == ["source:canonical-artifacts", "source:other"]) + try declaration.instructions?.sections == ["source:canonical-artifacts", "source:other"]) } @Test func editedTargetsFollowTheLockAndHandWrittenOnesNeedReplace() throws { @@ -186,12 +316,13 @@ struct InstructionExecutableTests { } } - @Test func updateApplyRewritesStateFromTheEarlierLayout() throws { + @Test func unchangedUpdatePreservesManifestAndLockFormatting() throws { let fixture = try CLIFixture() try fixture.instruction() try fixture.commit() try fixture.success(["instructions", "add", fixture.source.path, "--agent", "codex"]) - let files = [fixture.state("agents.json"), fixture.state("agents.resolved")] + let manifest = try Data(contentsOf: fixture.state("agents.yaml")) + let files = [fixture.state("agents.resolved")] let standard = try files.map { try Data(contentsOf: $0) } #expect(standard.allSatisfy { !String(decoding: $0, as: UTF8.self).contains("\" : ") }) for file in files { @@ -201,10 +332,12 @@ struct InstructionExecutableTests { #expect(String(decoding: earlier, as: UTF8.self).contains("\" : ")) try earlier.write(to: file) } - try fixture.success(["instructions", "update", "--apply"]) - #expect(try files.map { try Data(contentsOf: $0) } == standard) - try fixture.success(["instructions", "update", "--apply"]) - #expect(try files.map { try Data(contentsOf: $0) } == standard) + let before = try files.map { try Data(contentsOf: $0) } + for _ in 0..<2 { + try fixture.success(["instructions", "update", "--apply"]) + #expect(try files.map { try Data(contentsOf: $0) } == before) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == manifest) + } } @Test func addNamesTheSectionsEachTargetReceives() throws { @@ -275,16 +408,27 @@ struct InstructionExecutableTests { try String(contentsOf: target, encoding: .utf8) == generated(["# guide\n\nWrite the instructions here."])) let declaration = try fixture.declaration() - #expect((declaration["instructions"] as? [String: Any])?["sections"] as? [String] == ["guide"]) - try Data( - "---\ndescription: Guide.\n---\n# guide\n\nEdited instructions.\n".utf8 - ).write(to: own) - let install = try fixture.run(["install"]) + #expect(try declaration.instructions?.sections == ["guide"]) + let frozen = try Data(contentsOf: target) + let lock = try Data(contentsOf: fixture.state("agents.resolved")) + let edited = Data("---\ndescription: Guide.\n---\n# guide\n\nEdited instructions.\n".utf8) + try edited.write(to: own) + try FileManager.default.removeItem(at: target) + try fixture.success(["install"]) + #expect(try Data(contentsOf: target) == frozen) + #expect(try Data(contentsOf: own) == edited) + #expect(try Data(contentsOf: fixture.state("agents.resolved")) == lock) + let doctor = try fixture.run(["doctor", "--json"]) + #expect(doctor.status == 0 && doctor.stderr.isEmpty) + let roots = try #require(try doctor.json()["roots"] as? [[String: Any]]) + let checks = try #require(roots.first?["checks"] as? [[String: Any]]) #expect( - install.status == 1 - && install.stderr.hasSuffix( - "\n Run 'agents instructions update --apply' to regenerate targets from the edited file.\n" - )) + checks.contains { + $0["id"] as? String == "ownChanged" && $0["status"] as? String == "warning" + && $0["path"] as? String == own.path + }) + #expect(try Data(contentsOf: own) == edited) + #expect(try Data(contentsOf: fixture.state("agents.resolved")) == lock) try fixture.success(["instructions", "update", "--apply"]) #expect(try String(contentsOf: target, encoding: .utf8).contains("Edited instructions.")) let other = fixture.root.appendingPathComponent("other") @@ -315,7 +459,7 @@ struct InstructionExecutableTests { try fixture.success(["instructions", "add", fixture.source.path, "--agent", "codex"]) let target = fixture.project.appendingPathComponent("AGENTS.md") let bytes = try Data(contentsOf: target) - let declaration = try Data(contentsOf: fixture.state("agents.json")) + let declaration = try Data(contentsOf: fixture.state("agents.yaml")) let lock = try Data(contentsOf: fixture.state("agents.resolved")) let arguments = ["instructions", "update", "--agent", "cursor"] let recipients = "Recipients of AGENTS.md: codex -> cursor\n" @@ -341,7 +485,7 @@ struct InstructionExecutableTests { #expect(change["afterAgents"] as? [String] == ["cursor"]) #expect(change["before"] as? [String: String] == change["after"] as? [String: String]) #expect(try Data(contentsOf: target) == bytes) - #expect(try Data(contentsOf: fixture.state("agents.json")) == declaration) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == declaration) #expect(try Data(contentsOf: fixture.state("agents.resolved")) == lock) let applied = try fixture.success(arguments + ["--apply"]) #expect(applied.stdout.contains(recipients)) @@ -373,7 +517,7 @@ struct InstructionExecutableTests { ]) let forwarded = try String(contentsOf: claude, encoding: .utf8) #expect(forwarded.contains("@AGENTS.md") && forwarded.contains("Keep Claude custom content.")) - let before = try Data(contentsOf: fixture.state("agents.json")) + let before = try Data(contentsOf: fixture.state("agents.yaml")) let preview = try fixture.success(["instructions", "update", "--agent", "gemini-cli", "--json"]) .json() #expect(preview["changed"] as? Bool == true) @@ -397,7 +541,7 @@ struct InstructionExecutableTests { let diffIndex = try #require(human.stdout.range(of: header)?.lowerBound) #expect(recipientsIndex < diffIndex) } - #expect(try Data(contentsOf: fixture.state("agents.json")) == before) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == before) try fixture.success(["instructions", "update", "--agent", "gemini-cli", "--apply"]) #expect(try String(contentsOf: claude, encoding: .utf8) == custom) #expect( @@ -445,7 +589,8 @@ struct InstructionExecutableTests { }) let lock = try Data(contentsOf: fixture.state("agents.resolved")) let restored = try fixture.success(["install", "--json"]).json() - #expect(Set(restored.keys) == ["schemaVersion", "scope", "skills", "instructions"]) + #expect( + Set(restored.keys) == ["schemaVersion", "scope", "skills", "instructions", "components"]) #expect((restored["skills"] as? [[String: Any]])?.first?["name"] as? String == "demo") #expect((restored["instructions"] as? [String: Any])?["changed"] as? Bool == true) #expect(try Data(contentsOf: target) == originalTarget) @@ -536,7 +681,7 @@ struct InstructionExecutableTests { let update = try fixture.success(["update", "--json"]).json() #expect(update["changed"] as? Bool == false) #expect((update["instructions"] as? [String: Any])?["lockMissing"] as? Bool == true) - #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.json").path)) + #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.yaml").path)) let listing = try fixture.success(["instructions", "list"]) #expect(listing.stdout == "No managed project instructions.\n") } @@ -548,12 +693,9 @@ struct InstructionExecutableTests { .split(whereSeparator: \.isWhitespace).joined(separator: " ") #expect( help.contains( - "Set recipients of the scope's section list: codex, claude-code, cursor, gemini-cli or opencode." - )) - #expect( - help.contains( - "Default: the recorded instruction agents, else the declaration's agents, else codex and claude-code." + "Select recipients: codex, claude-code, cursor, gemini-cli, opencode, or antigravity." )) + #expect(help.contains("Omit to use the configured default recipients.")) } for command in [["add"], ["list"], ["remove"], ["update"], ["render", "chatgpt"]] { let help = try fixture.success(["instructions"] + command + ["--help"]).stdout @@ -625,20 +767,21 @@ extension CLIFixture { to: directory.appendingPathComponent(name + ".md")) } - func declaration(scope: String = "project") throws -> [String: Any] { - try #require( - JSONSerialization.jsonObject(with: Data(contentsOf: state("agents.json", scope: scope))) - as? [String: Any]) - } - func declarePrompt(scope: String = "project") throws { - var declaration = try declaration(scope: scope) - var instructions = try #require(declaration["instructions"] as? [String: Any]) - let sections = try #require(instructions["sections"] as? [String]) - instructions["chatgpt"] = ["weekly": ["sections": sections, "append": "prompt-custom.md"]] - declaration["instructions"] = instructions - try JSONSerialization.data(withJSONObject: declaration, options: [.sortedKeys]).write( - to: state("agents.json", scope: scope)) + let url = state("agents.yaml", scope: scope) + let document = try DeclarationDocument( + bytes: Array(Data(contentsOf: url)), identity: DocumentIdentity(url.path)) + let index = try declaration(scope: scope).skills?.isEmpty == false ? 1 : 0 + let node = try #require(document.node(at: "/components/\(index)")) + let change = try document.preparing([ + .upsertPrompt( + node, + NamedPromptDeclaration( + name: "weekly", + prompt: PromptDeclaration( + sections: ["source:canonical-artifacts"], append: "prompt-custom.md"))) + ]) + try Data(change.bytes).write(to: url) try Data("Custom prompt content.\n".utf8).write( to: (scope == "project" ? project : home).appendingPathComponent("prompt-custom.md")) } diff --git a/Tests/CLITests/ManifestExecutableTests.swift b/Tests/CLITests/ManifestExecutableTests.swift new file mode 100644 index 0000000..6bd4980 --- /dev/null +++ b/Tests/CLITests/ManifestExecutableTests.swift @@ -0,0 +1,306 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +struct ManifestExecutableTests { + @Test(arguments: ["project", "user"]) + func dumpPrintsProducerBytesAndSymbolicValues(_ scope: String) throws { + let fixture = try CLIFixture() + let source = """ + version: 1 + # Keep conditions, external references and runtime values symbolic. + defaultAgents: [opencode, codex] + sources: + remote: + url: https://example.invalid/never-fetch.git + components: + - kind: mcpServer + name: workspace + transport: + kind: stdio + executable: never-run + environment: + TOKEN: {secret: token} + condition: {scopes: [user], platforms: [linux]} + - kind: command + name: review + description: Review + prompt: {file: {path: missing-prompt.md}} + - kind: lspServer + name: swift + run: {executable: never-run} + languages: {.swift: swift} + initializationOptions: + whole: 1 + precise: !!float "1.00" + - kind: instructions + chatgpt: + weekly: + sections: [{name: own}] + uses: [{group: external, source: remote}] + """ + try fixture.writeManifest(source, scope: scope) + // The other scope must not influence selection. + try fixture.writeManifest("invalid other scope", scope: scope == "user" ? "project" : "user") + let url = fixture.state("agents.yaml", scope: scope) + let bytes = try Data(contentsOf: url) + let before = try FileManager.default.subpathsOfDirectory( + atPath: url.deletingLastPathComponent().path) + let result = try fixture.success(["manifest", "dump", "--json", "--scope", scope]) + #expect(Data(result.stdout.utf8) == Data(try ManifestDump(bytes: Array(bytes)).encodedJSON())) + #expect( + try fixture.success(["manifest", "dump", "--json", "--scope", scope]).stdout == result.stdout) + let dump = try result.json() + #expect( + Set(dump.keys) == [ + "schemaVersion", "kind", "format", "manifestVersion", "sourceDigest", "declaration", + "locations", + "diagnostics", + ]) + #expect(dump["schemaVersion"] as? Int == 2 && dump["kind"] as? String == "manifest") + #expect(dump["format"] as? String == "yaml" && dump["manifestVersion"] as? Int == 1) + let declaration = try #require(dump["declaration"] as? [String: Any]) + #expect(declaration["defaultAgents"] as? [String] == ["opencode", "codex"]) + #expect((declaration["uses"] as? [[String: Any]])?.first?["source"] as? String == "remote") + #expect( + result.stdout.contains("\"kind\": \"secret\"") && result.stdout.contains("missing-prompt.md")) + let locations = try #require(dump["locations"] as? [[String: Any]]) + #expect(!locations.isEmpty) + #expect( + locations.contains { + ($0["pointer"] as? String)?.hasPrefix("/components/3/chatGPT/0") == true + }) + let components = try #require(declaration["components"] as? [[String: Any]]) + let options = try #require(components[2]["initializationOptions"] as? [String: [String: Any]]) + #expect(options["whole"]?["kind"] as? String == "integer") + #expect(options["whole"]?["value"] as? Int == 1) + #expect(options["precise"]?["kind"] as? String == "decimal") + #expect(options["precise"]?["value"] as? String == "1.00") + #expect( + locations.allSatisfy { ($0["span"] as? [String: Any])?["document"] as? String == "manifest" }) + #expect(result.stdout.hasSuffix("\n") && !result.stdout.hasSuffix("\n\n")) + #expect( + !result.stdout.contains(fixture.project.path) && !result.stdout.contains(fixture.home.path)) + #expect(try Data(contentsOf: url) == bytes) + #expect( + try FileManager.default.subpathsOfDirectory(atPath: url.deletingLastPathComponent().path) + == before) + } + + @Test(arguments: [ + ("{}", "manifest.schema"), + ("version: 2", "manifest.schema"), + ("version: 1\nunknown: []", "manifest.schema"), + ("version: 1\ncomponents: [", "manifest.syntax"), + ("version: 1\ncomponents: {}", "manifest.schema"), + ]) + func malformedManifestHasLocatedDiagnostics(source: String, code: String) throws { + let fixture = try CLIFixture() + try fixture.writeManifest(source) + let before = try Data(contentsOf: fixture.state("agents.yaml")) + let result = try fixture.run(["manifest", "dump", "--json"]) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect(result.stderr.contains("agents.yaml:") && result.stderr.contains("[\(code)]")) + #expect(result.stderr.hasSuffix("\n Fix the reported agents.yaml diagnostics and retry.\n")) + #expect(!result.stderr.contains("ManifestFailure(") && !result.stderr.contains("metrics:")) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == before) + #expect( + try FileManager.default.contentsOfDirectory(atPath: fixture.state("").path) == [ + "agents.yaml" + ]) + } + + @Test(arguments: ["project", "user"]) + func missingManifestDoesNotCreateState(_ scope: String) throws { + let fixture = try CLIFixture() + let result = try fixture.run(["manifest", "dump", "--json", "--scope", scope]) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect( + result.stderr.contains("Not found: declaration at") + && result.stderr.contains("Create agents.yaml")) + #expect(!FileManager.default.fileExists(atPath: fixture.state("", scope: scope).path)) + } + + @Test(arguments: [ + ["manifest", "dump"], ["manifest", "dump", "--scope", "global", "--json"], + ["manifest", "dump", "--json", "--path", "other"], ["manifest", "dump", "other", "--json"], + ["manifest", "dump", "--json", "--apply"], ["manifest", "unknown", "--help"], + ]) + func usageErrors(_ arguments: [String]) throws { + let fixture = try CLIFixture() + let result = try fixture.run(arguments) + #expect(result.status == 64 && result.stdout.isEmpty) + #expect(result.stderr.hasSuffix("\n Run 'agents --help' for usage.\n")) + #expect(!FileManager.default.fileExists(atPath: fixture.state("").path)) + } + + @Test(arguments: [[], ["manifest"], ["manifest", "dump"]]) + func help(_ command: [String]) throws { + let fixture = try CLIFixture() + let result = try fixture.success(command + ["--help"]) + let option = command.isEmpty ? "manifest" : command == ["manifest"] ? "dump" : "--json" + #expect(result.stdout.contains(option)) + #expect(!FileManager.default.fileExists(atPath: fixture.state("").path)) + } + + @Test(arguments: ["project", "user"], ["agents.resolved", "agents.watch"]) + func orphanedStateIsReadOnly(scope: String, orphan: String) throws { + let fixture = try CLIFixture() + try fixture.skill() + try fixture.commit() + if orphan == "agents.watch" { + try fixture.success(["watch", "add", fixture.source.path, "--scope", scope]) + } else { + try fixture.success([ + "skills", "add", fixture.source.path, "--agent", "codex", "--scope", scope, + ]) + } + try FileManager.default.removeItem(at: fixture.state("agents.yaml", scope: scope)) + let url = fixture.state(orphan, scope: scope) + let before = try Data(contentsOf: url) + let paths = try FileManager.default.subpathsOfDirectory( + atPath: fixture.state("", scope: scope).path + ).sorted() + for command in [ + ["manifest", "dump"], ["skills", "list"], ["instructions", "list"], ["watch"], ["update"], + ] { + let result = try fixture.run(command + ["--json", "--scope", scope]) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect( + result.stderr.contains("Missing declaration at") + && result.stderr.contains("Restore agents.yaml")) + #expect(try Data(contentsOf: url) == before) + #expect( + try FileManager.default.subpathsOfDirectory(atPath: fixture.state("", scope: scope).path) + .sorted() == paths) + } + } + + @Test(arguments: ["project", "user"]) + func pendingRecoveryPrecedesParsingAndMissingDeclaration(_ scope: String) throws { + let fixture = try CLIFixture() + try fixture.writeManifest("invalid manifest", scope: scope) + let journal = fixture.state("transaction.new", scope: scope) + try Data("partial journal".utf8).write(to: journal) + let lock = fixture.state("agents.resolved", scope: scope) + try Data("incomplete lock".utf8).write(to: lock) + for missing in [false, true] { + if missing { + try FileManager.default.removeItem(at: fixture.state("agents.yaml", scope: scope)) + } + let paths = try FileManager.default.subpathsOfDirectory( + atPath: fixture.state("", scope: scope).path + ).sorted() + for command in [ + ["manifest", "dump"], ["skills", "list"], ["instructions", "list"], ["watch"], ["update"], + ] { + let result = try fixture.run(command + ["--json", "--scope", scope]) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect( + result.stderr.contains("Transaction recovery is pending") + && !result.stderr.contains("Recovered")) + #expect( + !result.stderr.contains("[manifest.") + && !result.stderr.contains("Missing declaration")) + #expect(try Data(contentsOf: journal) == Data("partial journal".utf8)) + #expect(try Data(contentsOf: lock) == Data("incomplete lock".utf8)) + #expect( + try FileManager.default.subpathsOfDirectory(atPath: fixture.state("", scope: scope).path) + .sorted() == paths) + } + } + } + + @Test(arguments: ["project", "user"]) + func lifecycleEditsPreserveCommentsAndNoOpBytes(_ scope: String) throws { + let fixture = try CLIFixture() + try fixture.skill() + try fixture.instruction() + try fixture.commit() + let prefix = """ + version: 1 + + # Team-owned defaults. Keep this spelling and spacing. + defaultAgents: [codex] + + """ + let manifest = + prefix + """ + sources: + # Local collection, shared by skills and instructions. + rules: + path: \(fixture.source.path.debugDescription) + components: [] # Deployment list. + watch: [] # Observations. + # Keep the footer. + """ + try fixture.writeManifest(manifest, scope: scope) + let options = ["--scope", scope] + for command in [ + ["skills", "add", "rules", "demo"], ["instructions", "add", "rules"], + ["watch", "add", "rules"], + ["instructions", "update", "--agent", "codex", "--apply"], + ["watch", "seen", "rules"], ["watch", "remove", "rules"], + ] { + try fixture.success(command + options) + let text = try String( + contentsOf: fixture.state("agents.yaml", scope: scope), encoding: .utf8) + #expect(text.hasPrefix(prefix)) + #expect(text.contains("# Local collection, shared by skills and instructions.")) + #expect( + text.contains("# Deployment list.") && text.contains("# Observations.") + && text.hasSuffix("# Keep the footer.\n")) + } + let files = ["agents.yaml", "agents.resolved", "agents.watch"].map { + fixture.state($0, scope: scope) + } + let before = try files.map { try Data(contentsOf: $0) } + for command in [ + ["update", "--apply"], ["install", "--json"], ["instructions", "update", "--apply"], + ] { + try fixture.success(command + options) + #expect(try files.map { try Data(contentsOf: $0) } == before) + } + let absent = try fixture.run(["skills", "remove", "absent"] + options) + #expect(absent.status == 1 && absent.stdout.isEmpty) + #expect(try files.map { try Data(contentsOf: $0) } == before) + for command in [ + ["skills", "remove", "demo"], ["instructions", "remove", "canonical-artifacts"], + ] { + try fixture.success(command + options) + let text = try String( + contentsOf: fixture.state("agents.yaml", scope: scope), encoding: .utf8) + #expect(text.hasPrefix(prefix) && text.hasSuffix("# Keep the footer.\n")) + } + } + + @Test(arguments: ["project", "user"]) + func unresolvedTransactionRequiresOwnerAndPreservesState(_ scope: String) throws { + let fixture = try CLIFixture() + try fixture.writeManifest("invalid manifest", scope: scope) + let journal = fixture.state("transaction.json", scope: scope) + try Data("{}".utf8).write(to: journal) + let result = try fixture.run(["doctor", "--json", "--scope", scope]) + #expect(result.status == 1 && result.stderr.isEmpty) + let roots = try #require(try result.json()["roots"] as? [[String: Any]]) + let checks = try #require(roots.first?["checks"] as? [[String: Any]]) + #expect( + checks.compactMap { $0["id"] as? String } == [ + "unresolved-transaction", "unresolvedTransaction", "unresolved-transaction", + ]) + #expect(checks.allSatisfy { $0["status"] as? String == "error" }) + #expect( + checks.allSatisfy { ($0["message"] as? String)?.contains("owner action is required") == true } + ) + let dump = try fixture.run(["manifest", "dump", "--json", "--scope", scope]) + #expect(dump.status == 1 && dump.stdout.isEmpty) + #expect( + dump.stderr.contains("Inspect the retained locations") + && !dump.stderr.contains("run 'agents install'")) + #expect(try Data(contentsOf: journal) == Data("{}".utf8)) + #expect( + try String(contentsOf: fixture.state("agents.yaml", scope: scope), encoding: .utf8) + == "invalid manifest\n") + } +} diff --git a/Tests/CLITests/MarketplaceExecutableTests.swift b/Tests/CLITests/MarketplaceExecutableTests.swift new file mode 100644 index 0000000..135de85 --- /dev/null +++ b/Tests/CLITests/MarketplaceExecutableTests.swift @@ -0,0 +1,471 @@ +import Foundation +import Testing + +struct MarketplaceExecutableTests { + @Test func codexPluginMarketplaceExportsChosenCategory() throws { + let fixture = try CLIFixture() + let project = fixture.root.appendingPathComponent("author") + try fixture.success([ + "bundle", "init", project.path, "--name", "team-tools", "--package-version", "1.0.0", + ]) + let spec = project.appendingPathComponent("author-package.json") + var document = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: spec)) as? [String: Any]) + var package = try #require(document["package"] as? [String: Any]) + package["author"] = "Example Team" + package["description"] = "Shared project tools" + document["package"] = package + try JSONSerialization.data(withJSONObject: document).write(to: spec) + + let output = fixture.root.appendingPathComponent("distribution") + let command = ["bundle", "plugin", "--target", "codex", "--marketplace", "team"] + let missing = try fixture.run(command + ["--output", output.path], directory: project) + #expect(missing.status != 0 && missing.stderr.contains("--category")) + #expect(!FileManager.default.fileExists(atPath: output.path)) + try fixture.success( + command + ["--category", "Productivity", "--output", output.path], directory: project) + let listing = output.appendingPathComponent(".agents/plugins/marketplace.json") + let catalog = try #require( + JSONSerialization.jsonObject(with: Data(contentsOf: listing)) as? [String: Any]) + let plugins = try #require(catalog["plugins"] as? [[String: Any]]) + #expect(plugins.first?["category"] as? String == "Productivity") + } + + @Test func directoryPublicationUsesTheSelectedScopeBeforeWriting() throws { + let fixture = try CLIFixture() + let author = fixture.root.appendingPathComponent("author") + try fixture.success([ + "bundle", "init", author.path, "--name", "team-kit", "--package-version", "1.0.0", + ]) + let archive = fixture.root.appendingPathComponent("team.agentsbundle") + try fixture.success(["bundle", "pack", "--output", archive.path], directory: author) + let catalog = fixture.root.appendingPathComponent("catalog") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: false) + + let rule = fixture.root.appendingPathComponent("source-policy.yaml") + try Data("version: 1\nallow: [inline]\n".utf8).write(to: rule) + try fixture.success(["policy", "set", rule.path, "--scope", "project", "--apply"]) + let publish = ["marketplace", "publish", archive.path, "--directory", catalog.path] + let denied = try fixture.run(publish + ["--scope", "project"]) + #expect(denied.status != 0 && denied.stderr.contains("project")) + #expect(try FileManager.default.contentsOfDirectory(atPath: catalog.path).isEmpty) + try fixture.success(publish + ["--scope", "user"]) + let release = catalog.appendingPathComponent("releases/team-kit/1.0.0/package.bundle") + #expect(try Data(contentsOf: release) == Data(contentsOf: archive)) + } + + @Test func graphResolutionUpgradeAndRemovalUseTheNamedCatalog() throws { + let fixture = try CLIFixture() + let market = try MarketplaceFixture(fixture) + try market.publish("shared", version: "1.0.0", members: ["scan"]) + try market.publish("shared", version: "2.0.0", members: ["scan"]) + try market.publish( + "starter", version: "1.0.0", members: ["scan", "relay"], + dependencies: ["shared@major:1.0.0"]) + try market.publish( + "extension", version: "1.0.0", members: ["relay"], dependencies: ["shared@major:1.0.0"]) + + let project = try market.consumer("consumer") + let state = project.appendingPathComponent(".agent") + let lock = state.appendingPathComponent("agents.resolved") + let manifest = state.appendingPathComponent("agents.yaml") + let fm = FileManager.default + let source = ["--catalog", "team"] + let discovery = try fixture.success( + ["marketplace", "resolve", "starter", "--json"] + source, directory: project + ).json() + let nodes = try #require(discovery["nodes"] as? [[String: Any]]) + let shared = try #require(nodes.first { nodePackage($0) == "shared" }) + #expect(shared["eligible"] as? String == "1.0.0") + #expect(shared["latest"] as? String == "2.0.0") + #expect(shared["locked"] == nil) + #expect(!fm.fileExists(atPath: state.path)) + + let ordinaryPreview = try fixture.success( + ["marketplace", "install", "starter", "--agent", "codex", "--json"] + source, + directory: project + ).json() + let ordinaryResolution = try #require(ordinaryPreview["resolution"] as? [String: Any]) + let ordinaryNodes = try #require(ordinaryResolution["nodes"] as? [[String: Any]]) + #expect(ordinaryNodes.contains { nodePackage($0) == "shared" }) + let ordinaryRoots = try #require(ordinaryResolution["roots"] as? [[String: Any]]) + let ordinarySelections = try #require(ordinaryRoots.first?["selections"] as? [[String: Any]]) + #expect(ordinarySelections.map { $0["package"] as? String } == ["starter", "starter"]) + let invalid = try fixture.run( + [ + "marketplace", "install", "starter", "--agent", "codex", "--requirement", "9.0.0", + "--apply", + ] + + source, directory: project) + #expect(invalid.status != 0) + #expect(!fm.fileExists(atPath: state.path)) + + let add = + ["marketplace", "install", "starter", "--alias", "base"] + source + [ + "--requirement", "major:1.0.0", + "--agent", "codex", "--member", "starter/mcpServer/relay", "--member", "shared/skills/scan", + ] + let preview = try fixture.success(add + ["--json"], directory: project).json() + #expect(preview["affectedRoots"] as? [String] == ["base"]) + let update = try #require(preview["update"] as? [String: Any]) + let components = try #require(update["components"] as? [[String: Any]]) + let relay = try #require(components.first { $0["name"] as? String == "relay" }) + let nativeConfig = try #require(relay["path"] as? String) + #expect(!fm.fileExists(atPath: state.path)) + #expect(!fm.fileExists(atPath: nativeConfig)) + try fixture.success(add + ["--apply"], directory: project) + let codex = project.appendingPathComponent(".agents/skills/scan/SKILL.md") + let claude = project.appendingPathComponent(".claude/skills/scan/SKILL.md") + #expect(fm.fileExists(atPath: codex.path)) + #expect(!fm.fileExists(atPath: claude.path)) + #expect(try String(contentsOfFile: nativeConfig, encoding: .utf8).contains("relay")) + try fixture.success( + ["marketplace", "install", "extension", "--alias", "extra", "--apply"] + source + [ + "--agent", "claude-code", "--member", "shared/skills/scan", + ], directory: project) + #expect(fm.fileExists(atPath: claude.path)) + + let installed = try fixture.success(["marketplace", "installed"], directory: project) + #expect(installed.stdout.contains("base starter 1.0.0")) + #expect(installed.stdout.contains("extra extension 1.0.0")) + let why = try fixture.success(["marketplace", "why", "shared"], directory: project) + #expect(why.stdout.contains("Required by root base")) + #expect(why.stdout.contains("Required by root extra")) + #expect(why.stdout.contains("major:1.0.0")) + + let coldFixture = try CLIFixture() + let cold = coldFixture.project + let coldState = cold.appendingPathComponent(".agent") + try fm.createDirectory(at: coldState, withIntermediateDirectories: true) + let coldLock = coldState.appendingPathComponent(lock.lastPathComponent) + try fm.copyItem(at: lock, to: coldLock) + try fm.copyItem(at: manifest, to: coldState.appendingPathComponent(manifest.lastPathComponent)) + let previousLock = try Data(contentsOf: lock) + let originalSkill = try Data(contentsOf: codex) + + let shadow = try market.consumer("shadow-catalog") + try fixture.success( + ["marketplace", "register", "team", "--directory", shadow.path], directory: project) + let rebound = try fixture.run(add + ["--apply"], directory: project) + #expect(rebound.status != 0) + #expect(try Data(contentsOf: lock) == previousLock) + try fixture.success(["marketplace", "unregister", "team"], directory: project) + + let updatedAuthor = try CLIFixture() + let updatedMarket = try MarketplaceFixture( + updatedAuthor, catalog: market.directory, skillBody: "Upgraded scan contents") + try updatedMarket.publish("shared", version: "1.1.0", members: ["scan"]) + let outdated = try fixture.success(["marketplace", "outdated", "base"], directory: project) + #expect(outdated.stdout.contains("locked 1.0.0 eligible 1.1.0 latest 2.0.0")) + let upgrade = ["marketplace", "upgrade", "base"] + let proposed = try fixture.success(upgrade + ["--json"], directory: project).json() + #expect(proposed["affectedRoots"] as? [String] == ["base", "extra"]) + #expect(try Data(contentsOf: lock) == previousLock) + #expect(try Data(contentsOf: codex) == originalSkill) + try fixture.success(upgrade + ["--apply"], directory: project) + #expect(try String(contentsOf: codex, encoding: .utf8).contains("Upgraded scan contents")) + #expect(try Data(contentsOf: claude) == Data(contentsOf: codex)) + + try fm.removeItem(at: market.directory) + try fm.removeItem(at: fixture.source) + try fm.removeItem(at: updatedAuthor.source) + let deps = try fixture.success(["marketplace", "deps"], directory: project) + #expect(deps.stdout.contains("shared locked 1.1.0")) + try coldFixture.success(["install"]) + #expect(try Data(contentsOf: coldLock) == previousLock) + #expect( + try Data(contentsOf: cold.appendingPathComponent(".agents/skills/scan/SKILL.md")) + == originalSkill) + try fixture.success(["marketplace", "remove", "base", "--apply"], directory: project) + #expect(!fm.fileExists(atPath: codex.path)) + #expect(fm.fileExists(atPath: claude.path)) + if fm.fileExists(atPath: nativeConfig) { + #expect(!(try String(contentsOfFile: nativeConfig, encoding: .utf8).contains("relay"))) + } + try fixture.success(["marketplace", "remove", "extra", "--apply"], directory: project) + #expect(!fm.fileExists(atPath: claude.path)) + #expect( + try fixture.success(["marketplace", "installed"], directory: project).stdout + .contains("No marketplace packages installed.")) + } + + @Test func metadataOnlyRecordsTheReleaseUntilMembersAreSelected() throws { + let fixture = try CLIFixture() + let market = try MarketplaceFixture(fixture) + try market.publish("toolkit", version: "1.0.0", members: ["scan"]) + let project = try market.consumer("metadata") + let install = ["marketplace", "install", "toolkit", "--catalog", "team"] + let skill = project.appendingPathComponent(".agents/skills/scan/SKILL.md") + try fixture.success(install + ["--metadata-only", "--apply"], directory: project) + let deps = try fixture.success(["marketplace", "deps"], directory: project) + #expect(deps.stdout.contains("toolkit locked 1.0.0")) + #expect(!FileManager.default.fileExists(atPath: skill.path)) + try fixture.success(install + ["--agent", "codex", "--apply"], directory: project) + #expect(FileManager.default.fileExists(atPath: skill.path)) + } + + @Test func exactMixedPackageKeepsItsExistingUpgradeAndPreviewContract() throws { + let fixture = try CLIFixture() + let market = try MarketplaceFixture(fixture) + try market.publish("toolkit", version: "1.0.0", members: ["scan", "relay"]) + let project = try market.consumer("legacy") + let install = [ + "marketplace", "install", "toolkit", "--catalog", "team", "--agent", "codex", + "--package-version", "1.0.0", + ] + let preview = try fixture.success(install + ["--json"], directory: project).json() + #expect(preview["schemaVersion"] as? Int == 2) + #expect(preview["marketplaceChanges"] != nil) + let components = try #require(preview["components"] as? [[String: Any]]) + let relay = try #require(components.first { $0["name"] as? String == "relay" }) + let native = try #require(relay["path"] as? String) + try fixture.success(install + ["--apply"], directory: project) + #expect(FileManager.default.fileExists(atPath: native)) + try market.publish("toolkit", version: "2.0.0", members: ["scan", "relay"]) + try fixture.success(["marketplace", "upgrade", "toolkit", "--apply"], directory: project) + let installed = try fixture.success(["marketplace", "installed"], directory: project) + #expect(installed.stdout.contains("toolkit toolkit 2.0.0")) + try market.publish("library", version: "1.0.0", members: ["scan"]) + try market.publish( + "toolkit", version: "3.0.0", members: ["scan", "relay"], dependencies: ["library@1.0.0"]) + try fixture.success(["marketplace", "upgrade", "toolkit", "--apply"], directory: project) + let deps = try fixture.success(["marketplace", "deps"], directory: project) + #expect(deps.stdout.contains("toolkit locked 3.0.0")) + #expect(deps.stdout.contains("library locked 1.0.0")) + #expect(try String(contentsOfFile: native, encoding: .utf8).contains("relay")) + try fixture.success(["marketplace", "remove", "toolkit", "--apply"], directory: project) + let skill = project.appendingPathComponent(".agents/skills/scan/SKILL.md") + #expect(!FileManager.default.fileExists(atPath: skill.path)) + } + + @Test func savesSelectedRecipientsThenDeploysOfflineFromTheLock() throws { + let fixture = try CLIFixture() + let market = try MarketplaceFixture(fixture) + try market.publish("toolkit", version: "1.0.0", members: ["scan"]) + let project = try market.consumer("consumer") + let install = [ + "marketplace", "install", "toolkit", "--catalog", "team", "--agent", "codex", "--lock-only", + ] + let fm = FileManager.default + let target = project.appendingPathComponent(".agents/skills/scan/SKILL.md") + let lock = project.appendingPathComponent(".agent/agents.resolved") + let preview = try fixture.success(install + ["--json"], directory: project).json() + let digest = try #require(preview["pendingDigest"] as? String) + #expect(digest.hasPrefix("sha256:") && digest.dropFirst(7).count == 64) + #expect(!fm.fileExists(atPath: lock.path)) + try fixture.success(install + ["--apply"], directory: project) + #expect(fm.fileExists(atPath: lock.path)) + #expect(!fm.fileExists(atPath: target.path)) + let pending = try fixture.run(["doctor", "--ci", "--json"], directory: project) + #expect(pending.status != 0 && pending.stdout.contains("pending-deployment")) + try fm.moveItem( + at: market.directory, to: fixture.root.appendingPathComponent("catalog-offline")) + try fixture.success(["marketplace", "deploy", "--json"], directory: project) + #expect(!fm.fileExists(atPath: target.path)) + try fixture.success(["marketplace", "deploy", "--apply"], directory: project) + #expect(try String(contentsOf: target, encoding: .utf8).contains("Original scan contents")) + try fixture.success(["doctor", "--ci"], directory: project) + } + + @Test func stagesUnmodifiedArchiveAndBindsCredentialsToUserCatalogs() throws { + let fixture = try CLIFixture() + let market = try MarketplaceFixture(fixture) + try market.publish("starter", version: "1.0.0", members: ["scan"]) + let archive = fixture.root.appendingPathComponent("starter-1.0.0.bundle") + let directory = try market.consumer("static-market") + let stage = ["marketplace", "stage", archive.path, "--directory", directory.path] + let first = try fixture.success(stage) + let index = directory.appendingPathComponent("marketplace.json") + #expect(first.stdout.trimmingCharacters(in: .whitespacesAndNewlines) == index.path) + let bytes = try Data(contentsOf: index) + let metadata = try #require(JSONSerialization.jsonObject(with: bytes) as? [String: Any]) + let releases = try #require(metadata["releases"] as? [[String: Any]]) + #expect(releases.count == 1) + let path = try #require(releases.first?["archivePath"] as? String) + #expect( + try Data(contentsOf: directory.appendingPathComponent(path)) == Data(contentsOf: archive)) + try fixture.success(stage) + #expect(try Data(contentsOf: index) == bytes) + + let indexURL = "https://catalog.example.invalid/team/marketplace.json" + let register = ["marketplace", "register", "private-team", "--index", indexURL] + try fixture.success(register + ["--scope", "project"]) + let search = [ + "marketplace", "search", "--catalog", "private-team", "--token-env", + "private-team=UNSET_TEST_TOKEN", + ] + let untrusted = try fixture.run(search) + #expect(untrusted.status != 0 && untrusted.stderr.contains("marketplace registration")) + try fixture.success(register + ["--scope", "user"]) + let missingToken = try fixture.run(search) + #expect(missingToken.status != 0 && missingToken.stderr.contains("empty or unset")) + } + + @Test func publishesOnlyTheReviewedAuthorProject() throws { + let fixture = try CLIFixture() + let project = fixture.root.appendingPathComponent("starter-project") + let catalog = fixture.root.appendingPathComponent("private-market") + try FileManager.default.createDirectory(at: catalog, withIntermediateDirectories: true) + try fixture.success([ + "bundle", "init", project.path, "--name", "starter", "--package-version", "1.0.0", + ]) + let review = try fixture.success(["bundle", "pack"], directory: project) + let line = try #require(review.stdout.split(separator: "\n").first { $0.hasPrefix("Digest ") }) + let digest = String(line.dropFirst("Digest ".count)) + let publish = ["bundle", "pack", "--publish-to", catalog.path, "--reviewed-digest", digest] + try fixture.success(publish, directory: project) + let skill = project.appendingPathComponent("skills/getting-started/SKILL.md") + var bytes = try Data(contentsOf: skill) + bytes.append(Data("\nChanged after review.\n".utf8)) + try bytes.write(to: skill) + let stale = try fixture.run(publish, directory: project) + #expect(stale.status != 0) + #expect( + !FileManager.default.fileExists( + atPath: project.appendingPathComponent(".agent/agents.resolved").path)) + let verified = try fixture.success( + ["marketplace", "verify", "--directory", catalog.path], directory: project) + #expect(verified.stdout.contains(digest)) + } + + @Test func reviewedMarketplaceAndBundlePathsDispatchWithSelectedRecipients() throws { + let fixture = try CLIFixture() + let market = try MarketplaceFixture(fixture) + try market.publish("toolkit", version: "1.0.0", members: ["scan"]) + let install = ["marketplace", "install", "toolkit", "--catalog", "team", "--agent", "codex"] + let archive = fixture.root.appendingPathComponent("toolkit-1.0.0.bundle").path + + let graph = try consumer("graph-lifecycle") + try fixture.success( + install + ["--requirement", "1.0.0", "--lock-only", "--json"], directory: graph) + #expect(!FileManager.default.fileExists(atPath: graph.appendingPathComponent("events").path)) + + try fixture.success( + install + ["--requirement", "1.0.0", "--lock-only", "--apply"], directory: graph) + let graphSkill = graph.appendingPathComponent(".agents/skills/scan/SKILL.md") + #expect(!FileManager.default.fileExists(atPath: graphSkill.path)) + try fixture.success(["marketplace", "lock", "--apply"], directory: graph) + try fixture.success(["marketplace", "deploy", "--apply"], directory: graph) + #expect(FileManager.default.fileExists(atPath: graphSkill.path)) + #expect( + !FileManager.default.fileExists( + atPath: graph.appendingPathComponent(".claude/skills/scan/SKILL.md").path)) + try fixture.success(["marketplace", "remove", "toolkit", "--apply"], directory: graph) + #expect(!FileManager.default.fileExists(atPath: graphSkill.path)) + #expect( + try events(graph) == [ + "pre-install", "post-install", "pre-update", "post-update", + "pre-install", "post-install", "pre-uninstall", "post-uninstall", + ]) + + let leaf = try consumer("leaf-lifecycle") + try fixture.success(install + ["--apply"], directory: leaf) + try fixture.success(["marketplace", "remove", "toolkit", "--apply"], directory: leaf) + #expect(try events(leaf) == ["pre-install", "post-install", "pre-uninstall", "post-uninstall"]) + + let bundle = try consumer("bundle-lifecycle") + let importBundle = ["bundle", "import", archive, "--agent", "claude-code"] + try fixture.success(["bundle", "inspect", archive], directory: bundle) + try fixture.success(importBundle + ["--json"], directory: bundle) + #expect(!FileManager.default.fileExists(atPath: bundle.appendingPathComponent("events").path)) + try fixture.success(importBundle + ["--apply"], directory: bundle) + #expect( + FileManager.default.fileExists( + atPath: bundle.appendingPathComponent(".claude/skills/scan/SKILL.md").path)) + #expect( + !FileManager.default.fileExists( + atPath: bundle.appendingPathComponent(".agents/skills/scan/SKILL.md").path)) + #expect(try events(bundle) == ["pre-install", "post-install"]) + + func consumer(_ name: String) throws -> URL { + let project = try market.consumer(name) + let state = project.appendingPathComponent(".agent") + try FileManager.default.createDirectory(at: state, withIntermediateDirectories: true) + let entries = [ + "pre-install", "post-install", "pre-update", "post-update", "pre-uninstall", + "post-uninstall", + ].map { event in + #" \#(event): [{type: command, run: 'printf "%s\n" \#(event) >> events'}]"# + }.joined(separator: "\n") + try Data(("version: 1\nlifecycle:\n" + entries + "\n").utf8).write( + to: state.appendingPathComponent("agents.yaml")) + try fixture.grantLifecycleTrust(in: project) + return project + } + + func events(_ project: URL) throws -> [String] { + try String(contentsOf: project.appendingPathComponent("events"), encoding: .utf8) + .split(separator: "\n").map(String.init) + } + } + + private func nodePackage(_ node: [String: Any]) -> String? { + (node["id"] as? [String: Any])?["package"] as? String + } +} + +private struct MarketplaceFixture { + let fixture: CLIFixture + let directory: URL + + init( + _ fixture: CLIFixture, catalog: URL? = nil, skillBody: String = "Original scan contents" + ) throws { + self.fixture = fixture + directory = catalog ?? fixture.home.appendingPathComponent("catalog") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try fixture.success([ + "marketplace", "register", "team", "--scope", "user", "--directory", + catalog?.path ?? "catalog", + ]) + try fixture.writeManifest( + """ + version: 1 + sources: + local: + path: \(fixture.source.path.debugDescription) + components: + - kind: skills + source: local + select: [scan] + mode: copy + agents: [codex] + - kind: mcpServer + name: relay + agents: [codex] + transport: + kind: stdio + executable: unpublished-fixture-relay + """) + try fixture.skill("scan", body: skillBody) + try fixture.commit() + try fixture.success(["update", "--apply"]) + } + + func publish( + _ name: String, version: String, members: [String], dependencies: [String] = [] + ) throws { + let report = try fixture.success(["components", "list", "--json"]).json() + let components = try #require(report["components"] as? [[String: Any]]) + let selections = try members.flatMap { name -> [String] in + let component = try #require(components.first { $0["name"] as? String == name }) + return ["--component", try #require(component["identity"] as? String)] + } + let archive = fixture.root.appendingPathComponent("\(name)-\(version).bundle").path + try fixture.success( + ["bundle", "export", archive, "--name", name, "--package-version", version] + + selections + dependencies.flatMap { ["--dependency", $0] }) + let inspected = try fixture.success(["bundle", "inspect", archive]) + for dependency in dependencies { + let requirement = dependency.replacingOccurrences(of: "@", with: " ") + #expect(inspected.stdout.contains("Requires " + requirement)) + } + try fixture.success(["marketplace", "publish", archive, "--catalog", "team"]) + } + + func consumer(_ name: String) throws -> URL { + let project = fixture.root.appendingPathComponent(name) + try FileManager.default.createDirectory(at: project, withIntermediateDirectories: true) + return project + } +} diff --git a/Tests/CLITests/PackageLifecycleExecutableTests.swift b/Tests/CLITests/PackageLifecycleExecutableTests.swift new file mode 100644 index 0000000..d95e0e6 --- /dev/null +++ b/Tests/CLITests/PackageLifecycleExecutableTests.swift @@ -0,0 +1,264 @@ +import Foundation +import Testing + +struct PackageLifecycleExecutableTests { + @Test func simulationTrustAndRevocationOfDeletedRoot() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + lifecycle: + post-install: + - type: command + run: 'printf success > simulated' + - type: command + run: 'exit 7' + """) + let review = try fixture.success(["lifecycle", "trust", "--json"]).json() + let rootID = try #require(review["rootID"] as? String) + let approval = try lifecycleTrustArguments(review) + let marker = fixture.project.appendingPathComponent("simulated") + let simulation = try fixture.success(["lifecycle", "test", "--json"]).json() + let actions = try #require(simulation["actions"] as? [[String: Any]]) + #expect(actions.count == 2) + #expect(actions.allSatisfy { $0["withholding"] as? String == "projectUntrusted" }) + #expect(!FileManager.default.fileExists(atPath: marker.path)) + + let grant = try fixture.run(["lifecycle", "trust", "--json"] + approval) + try #require(grant.status == 0, "\(grant.stderr)") + let executed = try fixture.run(["lifecycle", "test", "--execute", "--json"]) + #expect(executed.status == 1) + let results = try #require(try executed.json()["results"] as? [[String: Any]]) + #expect(results.map { $0["status"] as? String } == ["commandSucceeded", "commandFailed"]) + #expect(results.last?["exitStatus"] as? Int == 7) + #expect(try String(contentsOf: marker, encoding: .utf8) == "success") + + // A successful package operation reports a failing advisory action without failing itself. + let installed = try fixture.run(["install", "--json"]) + try #require(installed.status == 0, "\(installed.stderr)") + let lifecycle = try #require(try installed.json()["lifecycle"] as? [String: Any]) + let post = try #require(lifecycle["post"] as? [[String: Any]]) + #expect(post.map { $0["status"] as? String } == ["commandSucceeded", "commandFailed"]) + + try FileManager.default.removeItem(at: fixture.project) + let stored = try fixture.success(["lifecycle", "trusted", "--json"], directory: fixture.source) + let roots = try #require(try stored.json()["roots"] as? [[String: Any]]) + #expect(roots.first?["rootID"] as? String == rootID) + #expect(roots.first?["pathExists"] as? Bool == false) + let revoke = try fixture.run( + ["lifecycle", "untrust", "--root-id", rootID], directory: fixture.source) + #expect(revoke.status == 0) + let revoked = try fixture.success( + ["lifecycle", "trusted", "--json"], directory: fixture.source) + #expect((try revoked.json()["roots"] as? [[String: Any]])?.isEmpty == true) + } + + @Test func trustRejectsAChangedDigestOrReceiptRevision() throws { + let fixture = try CLIFixture() + let manifest = "version: 1\nlifecycle: {pre-update: [{type: command, run: 'exit 0'}]}" + try fixture.writeManifest(manifest) + let approval = try lifecycleTrustArguments( + fixture.success(["lifecycle", "trust", "--json"]).json()) + let unconfirmed = try fixture.run(["lifecycle", "trust", "--apply"]) + #expect(unconfirmed.status == 1) + try fixture.writeManifest(manifest.replacingOccurrences(of: "exit 0", with: "exit 5")) + let changed = try fixture.run(["lifecycle", "trust"] + approval) + #expect(changed.status == 1) + #expect(changed.stderr.contains("Review it again")) + try fixture.writeManifest(manifest) + try fixture.success(["lifecycle", "trust"] + approval) + try fixture.success(["lifecycle", "untrust"]) + let revoked = try fixture.run(["lifecycle", "trust"] + approval) + #expect(revoked.status == 1) + #expect(revoked.stderr.contains("trust receipt changed")) + } + + @Test(arguments: ["project", "user"]) + func scaffoldReviewsDocumentAndValidationReportsFields(scope: String) throws { + let fixture = try CLIFixture() + let scopeOption = ["--scope", scope] + let initCommand = ["lifecycle", "init"] + scopeOption + let manifest = fixture.state("agents.yaml", scope: scope) + let initial = "version: 1\n# owned formatting" + try fixture.writeManifest(initial, scope: scope) + let before = try Data(contentsOf: manifest) + let review = try fixture.success(initCommand + ["--json"]).json() + #expect(review["saved"] as? Bool == false) + #expect(try Data(contentsOf: manifest) == before) + let digest = try #require(review["digest"] as? String) + let apply = initCommand + ["--apply", "--reviewed-digest", digest] + try fixture.writeManifest(initial + "\n# changed after review", scope: scope) + let stale = try fixture.run(apply) + #expect(stale.status == 1) + #expect(stale.stderr.contains("differs from the reviewed scaffold")) + try fixture.writeManifest(initial, scope: scope) + try fixture.success(apply) + let scaffold = try String(contentsOf: manifest, encoding: .utf8) + #expect(scaffold.contains("# owned formatting")) + #expect(scaffold.contains("pre-install")) + let duplicate = try fixture.run(initCommand + ["--apply"]) + #expect(duplicate.status == 1) + try fixture.writeManifest( + "version: 1\nlifecycle: {pre-install: [{type: command, timeout: 301}]}", + scope: scope) + let invalid = try fixture.run(["lifecycle", "validate", "--json"] + scopeOption) + #expect(invalid.status == 1) + let diagnostics = try #require(try invalid.json()["diagnostics"] as? [[String: Any]]) + #expect( + diagnostics.contains { + $0["event"] as? String == "pre-install" && $0["index"] as? Int == 0 + && $0["field"] as? String == "timeout" + }) + let existing = "version: 1\nlifecycle: {pre-install: [{type: command, run: 'exit 0'}]}" + try fixture.writeManifest(existing, scope: scope) + let replacement = try fixture.success(initCommand + ["--force", "--json"]).json() + let replacementArguments = [ + "--force", "--apply", + "--reviewed-digest", try #require(replacement["digest"] as? String), + "--reviewed-original-digest", try #require(replacement["originalDigest"] as? String), + ] + try fixture.writeManifest( + existing.replacingOccurrences(of: "exit 0", with: "exit 5"), scope: scope) + let staleReplacement = try fixture.run(initCommand + replacementArguments) + #expect(staleReplacement.status == 1) + #expect((try String(contentsOf: manifest, encoding: .utf8)).contains("exit 5")) + try fixture.writeManifest(existing, scope: scope) + try fixture.success(initCommand + replacementArguments) + #expect(!(try String(contentsOf: manifest, encoding: .utf8)).contains("exit 0")) + } + + @Test func ordinaryCommandsDispatchTheirOwnEventsOnce() throws { + let fixture = try CLIFixture() + try fixture.skill() + try fixture.commit() + try fixture.success(["skills", "add", fixture.source.path, "demo"]) + let manifest = fixture.state("agents.yaml") + let contents = try String(contentsOf: manifest, encoding: .utf8) + let events = [ + "pre-install", "post-install", "pre-update", "post-update", "pre-compile", + "pre-uninstall", "post-uninstall", + ] + let entries = events.map { event in + #" \#(event): [{type: command, run: 'printf "%s\n" \#(event) >> events'}]"# + }.joined(separator: "\n") + try Data((contents + "\nlifecycle:\n" + entries + "\n").utf8).write(to: manifest) + try fixture.grantLifecycleTrust() + + let log = fixture.project.appendingPathComponent("events") + try fixture.success(["manifest", "dump", "--json"]) + for arguments in [ + ["update", "--json"], ["skills", "update", "--json"], ["instructions", "update", "--json"], + ] { + try fixture.success(arguments) + } + #expect(!FileManager.default.fileExists(atPath: log.path)) + try fixture.success(["install"]) + try fixture.success(["update", "--apply"]) + try fixture.success(["instructions", "update", "--apply"]) + try fixture.success(["skills", "remove", "demo", "--agent", "codex"]) + let dispatched = try String(contentsOf: log, encoding: .utf8) + #expect(dispatched.split(separator: "\n").map(String.init) == events) + #expect( + !FileManager.default.fileExists( + atPath: fixture.project.appendingPathComponent(".agents/skills/demo/SKILL.md").path)) + #expect( + FileManager.default.fileExists( + atPath: fixture.project.appendingPathComponent(".claude/skills/demo/SKILL.md").path)) + } + + @Test func projectAndUserInvocationsEachRunTheUserActionOnce() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + lifecycle: + pre-install: + - type: command + run: 'printf "%s\\n" "$APM_NO_SCRIPTS" >> user-events' + """, scope: "user") + try fixture.writeManifest( + "version: 1\nlifecycle: {pre-install: [{type: command, run: 'touch project-event'}]}") + let userView = try fixture.success(["lifecycle", "list", "--scope", "user", "--json"]).json() + let userActions = try #require(userView["actions"] as? [[String: Any]]) + #expect(userActions.map { $0["authority"] as? String } == ["user"]) + let projectView = try fixture.success(["lifecycle", "list", "--json"]).json() + let projectActions = try #require(projectView["actions"] as? [[String: Any]]) + #expect(projectActions.map { $0["authority"] as? String } == ["user", "project"]) + #expect(projectActions.last?["withholding"] as? String == "projectUntrusted") + + try fixture.success(["install", "--scope", "user"]) + try fixture.success(["install"]) + for directory in [fixture.home, fixture.project] { + let log = directory.appendingPathComponent("user-events") + #expect(try String(contentsOf: log, encoding: .utf8) == "1\n") + } + #expect( + !FileManager.default.fileExists( + atPath: fixture.project.appendingPathComponent("project-event").path)) + } + + @Test func interruptedTestCleansUpAndReportsTheChild() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + lifecycle: + post-install: + - type: command + run: 'kill -TERM "$PPID"; exec sleep 5' + - type: command + run: 'echo unexpected > next' + """) + try fixture.grantLifecycleTrust() + let result = try fixture.run(["lifecycle", "test", "--execute", "--json"]) + #expect(result.status == 1) + let report = try result.json() + #expect(report["interrupted"] as? Bool == true) + let results = try #require(report["results"] as? [[String: Any]]) + #expect(results.first?["status"] as? String == "commandCancelled") + #expect(results.first?["processGroupCleanedUp"] as? Bool == true) + #expect(results.last?["withholding"] as? String == "cancelled") + #expect( + !FileManager.default.fileExists(atPath: fixture.project.appendingPathComponent("next").path)) + } + + @Test func stalePackageReviewReportsPreExecutionAndSuppressesPost() throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + lifecycle: + pre-update: + - type: command + run: 'printf "pre\\n" >> events; printf "# changed by pre\\n" >> .agent/agents.yaml' + post-update: + - type: command + run: 'printf "post\\n" >> events' + """) + try fixture.grantLifecycleTrust() + let result = try fixture.run(["update", "--apply"]) + #expect(result.status == 1) + #expect(result.stdout.contains("commandSucceeded")) + #expect(result.stdout.contains("packageDidNotComplete")) + #expect( + try String(contentsOf: fixture.project.appendingPathComponent("events"), encoding: .utf8) + == "pre\n") + #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.resolved").path)) + } +} + +extension CLIFixture { + func grantLifecycleTrust(in directory: URL? = nil) throws { + let review = try success(["lifecycle", "trust", "--json"], directory: directory).json() + try success(["lifecycle", "trust"] + lifecycleTrustArguments(review), directory: directory) + } +} + +private func lifecycleTrustArguments(_ review: [String: Any]) throws -> [String] { + [ + "--apply", + "--reviewed-digest", try #require(review["digest"] as? String), + "--reviewed-root", try #require(review["rootID"] as? String), + "--reviewed-revision", String(try #require(review["revision"] as? Int)), + ] +} diff --git a/Tests/CLITests/ParsingTests.swift b/Tests/CLITests/ParsingTests.swift index f93a9d0..255faa5 100644 --- a/Tests/CLITests/ParsingTests.swift +++ b/Tests/CLITests/ParsingTests.swift @@ -107,6 +107,14 @@ struct ParsingTests { #expect(named.name == "demo") } + @Test(arguments: [ + ["skills", "add", ".", "--agent", "antigravity"], + ["skills", "list", "--agent", "antigravity"], ["doctor", "--agent", "antigravity"], + ]) + func antigravityRecipient(_ arguments: [String]) throws { + _ = try Agents.parseAsRoot(arguments) + } + @Test(arguments: [ ["unknown"], ["skills", "unknown"], ["skills", "add"], ["skills", "remove"], ["skills", "add", ".", "name", "--all"], ["skills", "add", ".", "--mode", "unknown"], diff --git a/Tests/CLITests/SkillOutputExecutableTests.swift b/Tests/CLITests/SkillOutputExecutableTests.swift index 36e56f9..b805494 100644 --- a/Tests/CLITests/SkillOutputExecutableTests.swift +++ b/Tests/CLITests/SkillOutputExecutableTests.swift @@ -47,7 +47,7 @@ struct SkillOutputExecutableTests { let revision = try fixture.revision() var previousMode = "link" for mode in ["copy", "edit", "link"] { - try changeSelection(fixture) { $0["mode"] = mode } + try fixture.declareSkills(mode: mode) let output = try fixture.success(["skills", "update", "--apply"]).stdout #expect( output.contains(" ~ changed codex (\(previousMode) -> \(mode)) .agents/skills/pdf\n")) @@ -86,7 +86,7 @@ struct SkillOutputExecutableTests { try fixture.skill("pdf") try fixture.commit() try fixture.success(["skills", "add", fixture.source.path, "pdf"]) - try changeSelection(fixture) { $0["agents"] = ["codex"] } + try fixture.declareSkills(agents: "[codex]") let revision = try fixture.revision() let partial = try fixture.success(["skills", "update", "--apply"]).stdout #expect(partial.contains("--- a/pdf/SKILL.md\n+++ /dev/null\n")) @@ -94,9 +94,10 @@ struct SkillOutputExecutableTests { #expect( partial.hasSuffix( "Removed pdf for claude-code.\nUpdated pdf for codex: \(revision) -> \(revision).\n")) - var declaration = try fixture.declaration() - declaration["skills"] = [String: Any]() - try JSONSerialization.data(withJSONObject: declaration).write(to: fixture.state("agents.json")) + try fixture.writeManifest( + """ + version: 1 + """) let removed = try fixture.success(["skills", "update", "--apply"]).stdout #expect(removed.contains("--- a/pdf/SKILL.md\n+++ /dev/null\n")) #expect(removed.hasSuffix("Removed pdf for codex.\n")) @@ -126,6 +127,16 @@ struct SkillOutputExecutableTests { ]) let fifo = fixture.project.appendingPathComponent(".agents/skills/broken/fifo") try #require(mkfifo(fifo.path, 0o600) == 0) + let fifoAttributes = try FileManager.default.attributesOfItem(atPath: fifo.path) + let broken = [".agents/skills/broken", ".claude/skills/broken"].map { + fixture.project.appendingPathComponent($0) + } + let brokenFiles = try broken.map { + try Data(contentsOf: $0.appendingPathComponent("SKILL.md")) + } + let brokenEntries = try broken.map { + try FileManager.default.contentsOfDirectory(atPath: $0.path).sorted() + } let list = try fixture.run(["skills", "list"]) #expect(list.status == 1) let before = try fixture.revision() @@ -137,6 +148,24 @@ struct SkillOutputExecutableTests { #expect(updated.hasSuffix("Updated healthy for claude-code, codex: \(before) -> \(after).\n")) let removed = try fixture.success(["skills", "remove", "healthy"]).stdout #expect(removed == "Removed healthy for claude-code, codex.\n") + for path in [".agents/skills/healthy", ".claude/skills/healthy"] { + #expect( + !FileManager.default.fileExists(atPath: fixture.project.appendingPathComponent(path).path)) + } + for (index, directory) in broken.enumerated() { + #expect( + try Data(contentsOf: directory.appendingPathComponent("SKILL.md")) == brokenFiles[index]) + #expect( + try FileManager.default.contentsOfDirectory(atPath: directory.path).sorted() + == brokenEntries[index]) + } + let currentFIFO = try FileManager.default.attributesOfItem(atPath: fifo.path) + #expect(currentFIFO[.type] as? FileAttributeType == fifoAttributes[.type] as? FileAttributeType) + #expect( + currentFIFO[.posixPermissions] as? NSNumber == fifoAttributes[.posixPermissions] as? NSNumber) + #expect( + currentFIFO[.systemFileNumber] as? NSNumber == fifoAttributes[.systemFileNumber] as? NSNumber) + #expect(currentFIFO[.systemNumber] as? NSNumber == fifoAttributes[.systemNumber] as? NSNumber) } @Test(arguments: ["update", "remove"]) @@ -166,14 +195,4 @@ struct SkillOutputExecutableTests { #expect(!FileManager.default.fileExists(atPath: journal.path)) } - private func changeSelection(_ fixture: CLIFixture, edit: (inout [String: Any]) -> Void) throws { - var declaration = try fixture.declaration() - var skills = try #require(declaration["skills"] as? [String: [String: Any]]) - let alias = try #require(skills.keys.first) - var selection = try #require(skills[alias]) - edit(&selection) - skills[alias] = selection - declaration["skills"] = skills - try JSONSerialization.data(withJSONObject: declaration).write(to: fixture.state("agents.json")) - } } diff --git a/Tests/CLITests/SourceSelectorTests.swift b/Tests/CLITests/SourceSelectorTests.swift index 4ee6ebd..5f04d14 100644 --- a/Tests/CLITests/SourceSelectorTests.swift +++ b/Tests/CLITests/SourceSelectorTests.swift @@ -2,12 +2,6 @@ import Foundation import Testing struct SourceSelectorTests { - private func declaration(_ fixture: CLIFixture) throws -> [String: Any] { - try #require( - JSONSerialization.jsonObject(with: Data(contentsOf: fixture.state("agents.json"))) - as? [String: Any]) - } - @Test func skillAddStoresSelectorsAsDeclarationFields() throws { let fixture = try CLIFixture() try fixture.skill("demo") @@ -16,11 +10,10 @@ struct SourceSelectorTests { try fixture.success([ "skills", "add", fixture.source.path + "@branch:main@skill:demo", "--agent", "codex", ]) - let declaration = try declaration(fixture) - let sources = try #require(declaration["sources"] as? [String: [String: String]]) - #expect(sources == ["source": ["local": fixture.source.path, "branch": "main"]]) - let skills = try #require(declaration["skills"] as? [String: [String: Any]]) - #expect(skills["source"]?["select"] as? [String] == ["demo"]) + let declaration = try fixture.declaration() + let source = try #require(declaration.sources["source"]) + #expect(source.location == fixture.source.path && source.requirement == .branch("main")) + #expect(try declaration.skills?["source"]?.select == .names(["demo"])) } @Test func instructionAddAcceptsRequirementsAndRejectsSkillSelectors() throws { @@ -37,8 +30,7 @@ struct SourceSelectorTests { try fixture.success([ "instructions", "add", fixture.source.path + "@branch:main", "rules", "--agent", "codex", ]) - let sources = try #require(try declaration(fixture)["sources"] as? [String: [String: String]]) - #expect(sources["source"]?["branch"] == "main") + #expect(try fixture.declaration().sources["source"]?.requirement == .branch("main")) } @Test func sourcesSharingALastComponentGetDistinctAliases() throws { @@ -51,7 +43,7 @@ struct SourceSelectorTests { try fixture.git(["clone", "--quiet", fixture.source.path, mirror.path]) try fixture.success(["skills", "add", fixture.source.path, "--agent", "codex"]) try fixture.success(["watch", "add", mirror.path]) - let sources = try #require(try declaration(fixture)["sources"] as? [String: Any]) + let sources = try fixture.declaration().sources #expect(Set(sources.keys) == ["source", "mirror-source"]) } } diff --git a/Tests/CLITests/UpdateReportingTests.swift b/Tests/CLITests/UpdateReportingTests.swift index d2bb405..3d6dac6 100644 --- a/Tests/CLITests/UpdateReportingTests.swift +++ b/Tests/CLITests/UpdateReportingTests.swift @@ -63,9 +63,10 @@ struct UpdateReportingTests { "Updated pdf for claude-code, codex: 1.3.0 (\(newRevision.prefix(7))) -> 1.4.0 (\(newRevision.prefix(7))).\n" )) #expect(!repinned.contains("mode pdf/")) - var declaration = try fixture.declaration() - declaration["skills"] = [String: Any]() - try JSONSerialization.data(withJSONObject: declaration).write(to: fixture.state("agents.json")) + try fixture.writeManifest( + """ + version: 1 + """) let removal = try fixture.success(command + ["--json"]).json() let removedSkill = try #require((removal["skills"] as? [[String: Any]])?.first) #expect(removedSkill["oldVersion"] as? String == "1.4.0") @@ -85,7 +86,7 @@ struct UpdateReportingTests { let steadySkill = try #require((steady["skills"] as? [[String: Any]])?.first) #expect(steadySkill["changed"] as? Bool == false) #expect((steadySkill["membership"] as? [Any])?.count == 2) - try selection(fixture) { $0["agents"] = ["claude-code", "cursor"] } + try fixture.declareSkills(mode: "edit", agents: "[claude-code, cursor]") let report = try fixture.success(command + ["--json"]).json() let skill = try #require((report["skills"] as? [[String: Any]])?.first) #expect(skill["oldVersion"] == nil && skill["newVersion"] == nil) @@ -138,7 +139,7 @@ struct UpdateReportingTests { #expect(preview.contains(" + added codex (edit) .agents/skills/pdf\n")) let failed = try fixture.run(command + ["--apply"]) #expect(failed.status == 1 && failed.stdout.isEmpty) - #expect(failed.stderr.contains("this scope does not manage")) + #expect(failed.stderr.contains("unmanaged content")) #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.resolved").path)) } @@ -198,11 +199,20 @@ struct UpdateReportingTests { try fixture.commit() try fixture.success(["instructions", "add", fixture.source.path]) try fixture.declarePrompt() - var declaration = try fixture.declaration() - var instructions = try #require(declaration["instructions"] as? [String: Any]) - instructions["sections"] = [String]() - declaration["instructions"] = instructions - try JSONSerialization.data(withJSONObject: declaration).write(to: fixture.state("agents.json")) + try fixture.writeManifest( + """ + version: 1 + sources: + source: + path: \(fixture.source.path.debugDescription) + components: + - kind: instructions + sections: [] + chatgpt: + weekly: + sections: [{name: canonical-artifacts, source: source}] + append: prompt-custom.md + """) try fixture.success(["update", "--apply"]) let locked = try Data(contentsOf: fixture.state("agents.resolved")) try Data("Unrelated source content\n".utf8).write( @@ -286,7 +296,7 @@ struct UpdateReportingTests { @Test(arguments: [ ( UpdateApplyDisposition.unchanged, "Update failed; no update was applied.", - "Check the scope's agents.json, agents.resolved, and recovery journal." + "Check the scope's agents.yaml, agents.resolved, and recovery journal." ), ( .committed, "Update committed, but a later step failed.", @@ -307,14 +317,4 @@ struct UpdateReportingTests { == "Error: \(outcome)\n Invalid state: fixture failure.\n \(remedy)\n") } - private func selection(_ fixture: CLIFixture, edit: (inout [String: Any]) -> Void) throws { - var declaration = try fixture.declaration() - var skills = try #require(declaration["skills"] as? [String: [String: Any]]) - let alias = try #require(skills.keys.first) - var value = try #require(skills[alias]) - edit(&value) - skills[alias] = value - declaration["skills"] = skills - try JSONSerialization.data(withJSONObject: declaration).write(to: fixture.state("agents.json")) - } } diff --git a/Tests/CLITests/WatchExecutableTests.swift b/Tests/CLITests/WatchExecutableTests.swift index b54d54d..a70c99a 100644 --- a/Tests/CLITests/WatchExecutableTests.swift +++ b/Tests/CLITests/WatchExecutableTests.swift @@ -9,18 +9,31 @@ struct WatchExecutableTests { try fixture.skill() try fixture.commit() let alias = "example.invalid/rules" - try FileManager.default.createDirectory( - at: fixture.state("agents.json").deletingLastPathComponent(), - withIntermediateDirectories: true) - try JSONSerialization.data(withJSONObject: [ - "sources": [ - alias: ["local": fixture.source.path], - "remote": ["git": "https://example.invalid/rules.git"], - ] - ]).write(to: fixture.state("agents.json")) + try fixture.writeManifest( + """ + version: 1 + sources: + \(alias.debugDescription): + path: \(fixture.source.path.debugDescription) + remote: + url: https://example.invalid/rules.git + """) let added = try fixture.success(["watch", "add", alias]) #expect(added.stdout.hasPrefix("Watching local:\(fixture.source.path) from ")) - #expect(try fixture.declaration()["watch"] as? [String] == [alias]) + #expect(try fixture.declaration().watch == [alias]) + } + + @Test(arguments: ["project", "user"]) + func addAcceptsDeclaredSourceIdentity(_ scope: String) throws { + let fixture = try CLIFixture() + try fixture.skill() + try fixture.commit() + let options = ["--scope", scope] + let sourceID = "local:" + fixture.source.path + try fixture.success(["watch", "add", fixture.source.path] + options) + let result = try fixture.success(["watch", "add", sourceID] + options) + #expect(result.stdout.hasPrefix("Watching \(sourceID) from ")) + #expect(try fixture.declaration(scope: scope).sources.count == 1) } @Test(arguments: ["project", "user"]) @@ -52,7 +65,6 @@ struct WatchExecutableTests { let initialSources = try #require(initialStatus["sources"] as? [[String: Any]]) let alias = try #require(initialSources.first?["alias"] as? String) #expect((initialSources.first?["changes"] as? [Any])?.isEmpty == true) - try fixture.success(["watch", "add", sourceID] + scopeOptions) try fixture.success(["watch", "add", alias] + scopeOptions) try fixture.success( @@ -82,7 +94,7 @@ struct WatchExecutableTests { try fixture.commit() let current = try fixture.git(["rev-parse", "HEAD"]).stdout.trimmingCharacters(in: .newlines) try fixture.skill("uncommitted", container: "collection/skills") - let declaration = try Data(contentsOf: fixture.state("agents.json", scope: scope)) + let declaration = try Data(contentsOf: fixture.state("agents.yaml", scope: scope)) let baseline = try Data(contentsOf: fixture.state("agents.watch", scope: scope)) let expected = """ @@ -144,7 +156,7 @@ struct WatchExecutableTests { "watch", "diff", fixture.source.path, "frontend-design", "--kind", "instructions", ] + scopeOptions ).stdout == "up to date\n") - #expect(try Data(contentsOf: fixture.state("agents.json", scope: scope)) == declaration) + #expect(try Data(contentsOf: fixture.state("agents.yaml", scope: scope)) == declaration) #expect(try Data(contentsOf: fixture.state("agents.watch", scope: scope)) == baseline) #expect(try Data(contentsOf: fixture.state("agents.resolved", scope: scope)) == lock) #expect(try Data(contentsOf: target) == installedBytes) @@ -164,7 +176,7 @@ struct WatchExecutableTests { #expect(try fixture.success(["watch"] + scopeOptions).stdout == "No watched sources.\n") #expect(try Data(contentsOf: target) == installedBytes) #expect(try Data(contentsOf: fixture.state("agents.resolved", scope: scope)) == lock) - #expect((try fixture.declaration(scope: scope)["sources"] as? [String: Any])?[alias] != nil) + #expect(try fixture.declaration(scope: scope).sources[alias] != nil) } @Test func modesLinksBinaryAndKindFiltering() throws { diff --git a/Tests/CLITests/WatchReportTests.swift b/Tests/CLITests/WatchReportTests.swift index bbe3c27..97a0fa6 100644 --- a/Tests/CLITests/WatchReportTests.swift +++ b/Tests/CLITests/WatchReportTests.swift @@ -6,22 +6,30 @@ import Testing @testable import CLI struct WatchReportTests { - @Test func confirmationUsesSubscribedAliasThenSubscribedIdentity() throws { + @Test func watchChangesReturnConfirmedIdentity() throws { let fixture = try CLIFixture() let environment = RuntimeEnvironment( projectDirectory: fixture.project, homeDirectory: fixture.home, environment: fixture.environment) let id = "example.invalid/rules" - var declaration = Declaration( - sources: [ - id: SourceDeclaration(kind: .local, location: fixture.source.path), - "remote": SourceDeclaration(kind: .git, location: "https://example.invalid/rules.git"), - ], watch: ["remote"]) - #expect(try watchedSourceID(id, declaration: declaration, environment: environment) == id) - declaration.watch = [id, "remote"] - #expect( - try watchedSourceID(id, declaration: declaration, environment: environment) == "local:" - + fixture.source.path) + try fixture.skill() + try fixture.commit() + try fixture.writeManifest( + """ + version: 1 + sources: + \(id.debugDescription): + path: \(fixture.source.path.debugDescription) + remote: + url: https://example.invalid/rules.git + """) + let operations = SkillOperations.watchOperations() + let added = try operations.add(id, environment: environment) + #expect(added.alias == id && added.sourceID == "local:" + fixture.source.path) + let seen = try operations.seen(id, environment: environment) + #expect(seen.alias == id && seen.sourceID == added.sourceID && seen.seen == added.seen) + let removed = try operations.remove(id, environment: environment) + #expect(removed.alias == id && removed.sourceID == added.sourceID && removed.seen == nil) } @Test func wellKnownRenderingAndDigests() throws {