From 71109de18001358098ab9846b9b21c8a2cdaf10a Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 28 Oct 2026 18:46:16 +0800 Subject: [PATCH 01/67] docs(decisions): record product scope and front ends --- Documentation/Decisions/FrontEnds.md | 73 +++++++++++++++++++++++++ Documentation/Decisions/ProductScope.md | 59 ++++++++++++++++++++ Documentation/Decisions/README.md | 6 ++ 3 files changed, 138 insertions(+) create mode 100644 Documentation/Decisions/FrontEnds.md create mode 100644 Documentation/Decisions/ProductScope.md diff --git a/Documentation/Decisions/FrontEnds.md b/Documentation/Decisions/FrontEnds.md new file mode 100644 index 0000000..1c27675 --- /dev/null +++ b/Documentation/Decisions/FrontEnds.md @@ -0,0 +1,73 @@ +# 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.swift`, 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.swift` and the lock and running + `agents install`. +- **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 a pending executable component. 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.swift`. + +## 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) +- Executable approval the GUI presents: [core decisions](https://github.com/agents-tools/core/tree/master/Documentation/Decisions) +- Current architecture: [Architecture](../Architecture/README.md) diff --git a/Documentation/Decisions/ProductScope.md b/Documentation/Decisions/ProductScope.md new file mode 100644 index 0000000..124471e --- /dev/null +++ b/Documentation/Decisions/ProductScope.md @@ -0,0 +1,59 @@ +# 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. +- **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.swift`. + +## 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, components and approval: [core decisions](https://github.com/agents-tools/core/tree/master/Documentation/Decisions) +- 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. From 52b8af928090f9c65649692dbd24ea01869558ad Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:00:19 +0800 Subject: [PATCH 02/67] feat: adopt Swift agent declarations --- .github/swift-package.json | 10 +- CONTRIBUTING.md | 2 +- Documentation/README.md | 2 + Documentation/Reference/CLI.md | 127 +++++--- Documentation/Reference/ManifestDump.md | 27 ++ Documentation/Reference/Release.md | 2 +- .../Reference/Schemas/doctor.schema.json | 3 +- Package.resolved | 32 +- Package.swift | 12 +- README.md | 30 +- Sources/CLI/EntryPoint.swift | 16 +- Sources/CLI/InstructionCommands.swift | 32 +- Sources/CLI/JSONReports.swift | 6 +- Sources/CLI/LifecycleCommands.swift | 6 +- Sources/CLI/LineDiff.swift | 2 +- Sources/CLI/ManifestCommands.swift | 32 ++ Sources/CLI/Options.swift | 4 +- Sources/CLI/SkillCommands.swift | 15 +- Sources/CLI/Terminal.swift | 48 ++- Sources/CLI/WatchCommands.swift | 85 +---- Sources/CLI/WatchReports.swift | 6 +- Tests/CLITests/CLIFixture.swift | 29 ++ Tests/CLITests/ExecutableTests.swift | 23 +- Tests/CLITests/HumanExecutableTests.swift | 23 +- .../CLITests/InstructionExecutableTests.swift | 66 ++-- Tests/CLITests/ManifestExecutableTests.swift | 297 ++++++++++++++++++ .../CLITests/SkillOutputExecutableTests.swift | 23 +- Tests/CLITests/SourceSelectorTests.swift | 20 +- Tests/CLITests/UpdateReportingTests.swift | 42 +-- Tests/CLITests/WatchExecutableTests.swift | 40 ++- Tests/CLITests/WatchReportTests.swift | 30 +- 31 files changed, 781 insertions(+), 311 deletions(-) create mode 100644 Documentation/Reference/ManifestDump.md create mode 100644 Sources/CLI/ManifestCommands.swift create mode 100644 Tests/CLITests/ManifestExecutableTests.swift diff --git a/.github/swift-package.json b/.github/swift-package.json index 35a9e8a..69406c7 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -2,5 +2,13 @@ "compilers": [ {"name": "macos-26-xcode-26.6", "runner": "macos-26", "xcode": "26.6"} ], - "demo": {"product": "agents"} + "demo": {"product": "agents"}, + "platforms": { + "linux": [ + { + "name": "linux-swift-6.4.1", + "image": "swift:6.4.1-noble@sha256:6304481cf2717966b7ba175162e397ea2f2cc3161909f2b2a5cf40036079a0f7" + } + ] + } } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 112e264..a6b8f3a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -7,7 +7,7 @@ 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 +Build with Swift 6.3 or later on macOS 15 or later, or Linux. Shared CI compiles and tests only with Xcode 26.6 on `macos-26`. Package validation is configured in [.github/swift-package.json](.github/swift-package.json) diff --git a/Documentation/README.md b/Documentation/README.md index 742f91c..e338d40 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -12,6 +12,8 @@ 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. +- [Manifest dump](Reference/ManifestDump.md): producer-owned language JSON contract + exposed by `agents manifest dump --json`. - [JSON schemas](Reference/Schemas/): machine-readable schemas for list, update previews, watch status and diffs, installation, and doctor. - [Release checklist](Reference/Release.md): prepare and verify release commits, diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index fb7dadf..1735441 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -2,7 +2,8 @@ `agents` manages declared skills and instructions. Resolution, installation, state, and recovery operations use `AgentsCore`, `AgentsSkills`, and -`AgentsInstructions`; top-level updates use `AgentsUpdates`. +`AgentsInstructions`; top-level updates use `AgentsUpdates`. `AgentsManifest` +owns declaration parsing and editing, and the manifest dump contract. ## Commands @@ -25,13 +26,15 @@ 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 manifest dump --json [--scope project|user] agents install [--json] agents update [--apply | --json] agents doctor [--root …] [--json] ``` `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`, 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 @@ -64,7 +67,7 @@ Examples: | `--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`; `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 @@ -105,16 +108,16 @@ 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 map to the arguments of `.source` in `Agents.swift`: | 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` | `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(from: "1.2.3")` | At least 1.2.3, below 1.3.0 | +| `--from 1.2.3 --to 1.8.0` | `"1.2.3"..<"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 +141,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.swift` 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 `. @@ -208,24 +211,31 @@ 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.swift`, using an existing source alias (here `rules`): -```json -{ - "instructions": { - "sections": ["rules:canonical-artifacts"], - "chatgpt": { - "weekly": { - "sections": ["rules:canonical-artifacts"], - "append": "prompt-custom.md" - } - } - } -} +```swift +// agents-tools-version: 1.0 +import AgentsDescription + +let agents = Agents( + sources: [.source(name: "rules", path: "../team-rules")], + components: [ + .instructions( + sections: [.section(name: "canonical-artifacts", source: "rules")], + chatGPT: [ + .prompt( + name: "weekly", + sections: [.section(name: "canonical-artifacts", source: "rules")], + append: "prompt-custom.md" + ), + ] + ), + ] +) ``` -Merge this fragment with the declaration's existing sources and selections. +Add the `.prompt` to the instructions component's `chatGPT` list. `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 +249,23 @@ 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.swift` under a shared lock and prints core's evaluated 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 evaluates the local static language without resolving external groups, +fetching sources or secrets, inspecting native files, or compiling or running +Swift code. 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. Syntax, type +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. + ## Watch `watch add ` subscribes without installing content and records the @@ -314,7 +341,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.swift` 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 @@ -537,16 +564,22 @@ 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.swift` | `.agent/agents.resolved` | `.agent/cache/` | +| User | `~/.agents/Agents.swift` | `~/.agents/agents.resolved` | `~/.agents/cache/` | + +A project commits its declaration and lock; the cache stays local. `Agents.swift` +uses the [manifest language](https://github.com/agents-tools/core/blob/a2d734fb14cf2d93e7ddd8a6087d7c90453abea4/Documentation/Reference/Manifest.md), +a statically evaluated Swift subset with a required version directive and +`import AgentsDescription`. Lifecycle commands use core's deployable subset. +Unsupported deployment constructs produce located diagnostics; dump accepts the +complete language. 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. The lock remains 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.swift` 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 +599,11 @@ 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. ## Output and Exit Status @@ -587,14 +625,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 with .prompt in the instructions component of Agents.swift 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.swift` as +`.source(name: "missing", url: "file://localhost/missing/skills.git")`, a failed add reports: ```text $ agents skills add missing demo @@ -624,8 +662,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,6 +673,10 @@ one object and a trailing newline; recovery notices remain on stderr. ## JSON Schemas +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 update, instruction update and install reports, 1 for the others. Object keys are sorted. Arrays follow core's deterministic ordering; instruction section lists preserve @@ -653,6 +697,7 @@ 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 language 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` | diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md new file mode 100644 index 0000000..077d14a --- /dev/null +++ b/Documentation/Reference/ManifestDump.md @@ -0,0 +1,27 @@ +# Manifest Dump Contract + +`agents manifest dump --json [--scope project|user]` exposes the manifest +language's evaluated JSON schema. The authoritative schema and byte contract +are core's [Evaluated JSON Dump](https://github.com/agents-tools/core/blob/a2d734fb14cf2d93e7ddd8a6087d7c90453abea4/Documentation/Reference/Manifest.md#evaluated-json-dump), +including its construction vocabulary 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: 1`, `kind: "manifest"` and +`languageVersion: "1.0"`. It contains `sourceDigest`, `declaration`, `locations` +and `diagnostics`. These fields, their normalized values, discriminants, +ordering and defaults are owned by the linked language contract. Locations +use the stable document identity `manifest`, with UTF-8 byte offsets and +1-based line/byte-column coordinates. 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). +Other [CLI JSON schemas](CLI.md#json-schemas) describe independent report shapes; +they do not describe declaration storage or this language object. diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index 5e9b71e..d53d90d 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -39,7 +39,7 @@ 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 +On macOS, 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`. Use a clean task or detached worktree at the exact merged release candidate. diff --git a/Documentation/Reference/Schemas/doctor.schema.json b/Documentation/Reference/Schemas/doctor.schema.json index e184bf0..050dc68 100644 --- a/Documentation/Reference/Schemas/doctor.schema.json +++ b/Documentation/Reference/Schemas/doctor.schema.json @@ -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": [ diff --git a/Package.resolved b/Package.resolved index 3ed545f..4b96759 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,13 +1,12 @@ { - "originHash" : "586b1f666f366ef83112773c577dff68045cc8c33f80d0d3326da317163ec154", + "originHash" : "e6051e2863ae30bcbb5dc71e47ff6e9fe7f381268509a8ad6c2debc0c02d0493", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "65df60ef97ff6d347b6944372a1b75de919313fe", - "version" : "0.2.0" + "revision" : "a2d734fb14cf2d93e7ddd8a6087d7c90453abea4" } }, { @@ -19,6 +18,15 @@ "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-cmark", "kind" : "remoteSourceControl", @@ -28,6 +36,15 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-crypto", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-crypto.git", + "state" : { + "revision" : "f8fad2f95ad67b45f6340c0960e2396094d67e07", + "version" : "5.1.1" + } + }, { "identity" : "swift-markdown", "kind" : "remoteSourceControl", @@ -37,6 +54,15 @@ "version" : "0.9.0" } }, + { + "identity" : "swift-syntax", + "kind" : "remoteSourceControl", + "location" : "https://github.com/swiftlang/swift-syntax.git", + "state" : { + "revision" : "050f1a346fbbac0ca2cfb15a95274f7bd1cf0ccf", + "version" : "604.0.0" + } + }, { "identity" : "yams", "kind" : "remoteSourceControl", diff --git a/Package.swift b/Package.swift index 4a9a622..321f7b4 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", + revision: "a2d734fb14cf2d93e7ddd8a6087d7c90453abea4"), ], targets: [ .executableTarget( @@ -16,11 +18,17 @@ 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"), + .product(name: "AgentsDescription", package: "core"), + ]), ], swiftLanguageModes: [.v6] ) diff --git a/README.md b/README.md index 7bf097e..8a199ab 100644 --- a/README.md +++ b/README.md @@ -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: @@ -108,8 +108,14 @@ 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 ``` +Declarations live in `.agent/Agents.swift` for project scope or +`~/.agents/Agents.swift` for user scope. The [manifest language](https://github.com/agents-tools/core/blob/a2d734fb14cf2d93e7ddd8a6087d7c90453abea4/Documentation/Reference/Manifest.md) +is a statically evaluated Swift subset. `agents manifest dump --json` prints the +local declaration and its 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. @@ -127,7 +133,7 @@ remove, or update sets the recipients of the scope's entire section list. `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.swift` 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 @@ -136,7 +142,7 @@ All three support combined `--json` reports. ## Requirements -- macOS 15 or later. +- macOS 15 or later, or Linux (source build). - Swift 6.3 or later to build from source. - Git for Git-backed sources. @@ -159,7 +165,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 +183,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 ``` diff --git a/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index aac60de..781eb0c 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -1,7 +1,12 @@ import ArgumentParser -import Darwin import Foundation +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + enum BuildInfo { static let version = "0.2.0" } @@ -21,7 +26,8 @@ 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, ] ) @@ -61,7 +67,7 @@ enum EntryPoint { } Terminal.error( Agents.message(for: error), remedy: "Run 'agents --help' for usage.") - Darwin.exit(64) + exit(64) } do { try command.run() @@ -72,11 +78,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/InstructionCommands.swift b/Sources/CLI/InstructionCommands.swift index 0fd8beb..c64682e 100644 --- a/Sources/CLI/InstructionCommands.swift +++ b/Sources/CLI/InstructionCommands.swift @@ -1,5 +1,6 @@ import AgentsCore import AgentsInstructions +import AgentsManifest import ArgumentParser import Foundation @@ -106,20 +107,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) @@ -198,22 +195,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 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/JSONReports.swift b/Sources/CLI/JSONReports.swift index 7a63162..18fa434 100644 --- a/Sources/CLI/JSONReports.swift +++ b/Sources/CLI/JSONReports.swift @@ -251,7 +251,9 @@ struct CheckItem: Encodable { init(_ check: DoctorCheck, environment: RuntimeEnvironment) { kind = "skills" id = check.id - status = check.id == "pending-recovery" ? "error" : check.status.rawValue + status = + ["pending-recovery", "unresolved-transaction"].contains(check.id) + ? "error" : check.status.rawValue message = check.id == "pending-recovery" ? Self.pendingRecoveryMessage(path: check.path, environment: environment) : check.message @@ -263,7 +265,7 @@ struct CheckItem: Encodable { id = diagnostic.kind.rawValue switch diagnostic.kind { case .invalidTarget, .foreignTarget, .invalidLink, .invalidConfiguration, .stateUnavailable, - .pendingRecovery: + .pendingRecovery, .unresolvedTransaction: status = "error" default: status = "warning" diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index 7c9a90c..442f7ff 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -54,13 +54,14 @@ struct UpdateOptions: ParsableArguments { } func updateSkills(names: [String] = []) throws -> [UpdateResult] { - try withRecovery { + func operation() throws -> [UpdateResult] { try SkillOperations.updateInstalled( scope: location.scope, skillNames: names, apply: apply, beforeApply: { results in Terminal.differences(results, paths: location.paths) }) } + return try apply ? withRecovery(operation) : operation() } func finishSkills(_ results: [UpdateResult]) { @@ -74,13 +75,14 @@ struct UpdateOptions: ParsableArguments { func updateInstructions(agents: [AgentID]? = nil, replace: Bool = false) throws -> InstructionUpdateReport { - try withRecovery { + func operation() throws -> InstructionUpdateReport { try InstructionOperations.updateInstalled( scope: location.scope, agents: agents, apply: apply, replace: replace, beforeApply: { result in Terminal.instructionDifferences(result, paths: location.paths) }) } + return try apply ? withRecovery(operation) : operation() } func finishInstructions(_ result: InstructionUpdateReport) { 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/ManifestCommands.swift b/Sources/CLI/ManifestCommands.swift new file mode 100644 index 0000000..0ca9095 --- /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 the scope's Agents.swift declaration.", + subcommands: [DumpManifest.self]) +} + +struct DumpManifest: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "dump", abstract: "Print the local manifest's evaluated JSON and source locations." + ) + + @OptionGroup var location: ScopeOptions + @Flag(help: "Print the manifest language 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/Options.swift b/Sources/CLI/Options.swift index cdec88a..b6fc2fa 100644 --- a/Sources/CLI/Options.swift +++ b/Sources/CLI/Options.swift @@ -75,9 +75,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/SkillCommands.swift b/Sources/CLI/SkillCommands.swift index 9909e8a..acbf90c 100644 --- a/Sources/CLI/SkillCommands.swift +++ b/Sources/CLI/SkillCommands.swift @@ -71,12 +71,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 +82,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 { diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index e022d86..5550931 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.swift 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.swift from version control before retrying" + case CoreError.notFound where command is DumpManifest: + action = + "create Agents.swift 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.swift, agents.resolved, and recovery journal" case CoreError.commandFailed: action = "check the command arguments and filesystem permissions" case InstructionError.unownedTargets: @@ -128,10 +147,10 @@ enum Terminal { "link only to files in the checkout being written, or name the file in text without a link" case HumanOutputError.undeclaredPrompt: action = - "declare it under instructions.chatgpt in agents.json and run 'agents instructions update --apply'" + "declare it with .prompt in the instructions component of Agents.swift 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.swift and run 'agents instructions update --apply'" case is InstructionError: action = "check the instruction source and target Markdown with 'agents doctor'" default: @@ -141,8 +160,21 @@ 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 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 +186,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( 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/CLIFixture.swift b/Tests/CLITests/CLIFixture.swift index 6e59b49..20bbb87 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,33 @@ 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.swift", 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 = "[.claudeCode, .codex]") throws { + try writeManifest( + """ + // agents-tools-version: 1.0 + import AgentsDescription + let agents = Agents( + sources: [.source(name: "source", path: \(source.path.debugDescription))], + components: [.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/ExecutableTests.swift b/Tests/CLITests/ExecutableTests.swift index 469cd20..59c5b53 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.swift", 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]]) @@ -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.swift", 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.swift").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.swift").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.swift", 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]), ]) { @@ -251,8 +252,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 +274,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 { diff --git a/Tests/CLITests/HumanExecutableTests.swift b/Tests/CLITests/HumanExecutableTests.swift index 245e6c9..2b66b88 100644 --- a/Tests/CLITests/HumanExecutableTests.swift +++ b/Tests/CLITests/HumanExecutableTests.swift @@ -7,12 +7,12 @@ 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( + """ + // agents-tools-version: 1.0 + import AgentsDescription + let agents = Agents(sources: [.source(name: "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")) @@ -200,12 +200,7 @@ 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( @@ -220,7 +215,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 with .prompt in the instructions component of Agents.swift and run 'agents instructions update --apply'.\n" ) #expect(!FileManager.default.fileExists(atPath: fixture.state("").path)) try fixture.instruction() @@ -237,7 +232,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.swift 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..71de2f2 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -1,4 +1,7 @@ +import AgentsCore +import AgentsDescription import AgentsInstructions +import AgentsManifest import Foundation import Testing @@ -41,7 +44,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.swift", scope: scope)) let lock = try Data(contentsOf: fixture.state("agents.resolved", scope: scope)) let preview = try fixture.success(["instructions", "update"] + arguments) #expect( @@ -57,7 +60,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.swift", 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 +104,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.swift").path)) let discovered = try fixture.success(["instructions", "list"] + sourceArguments + ["--json"]) .json() #expect(discovered["kind"] as? String == "source") @@ -131,9 +134,7 @@ 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"]) + #expect(declaration.instructions?.sections == ["source:canonical-artifacts", "source:other"]) } @Test func editedTargetsFollowTheLockAndHandWrittenOnesNeedReplace() throws { @@ -186,12 +187,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.swift")) + 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 +203,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.swift")) == manifest) + } } @Test func addNamesTheSectionsEachTargetReceives() throws { @@ -275,7 +279,7 @@ 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"]) + #expect(declaration.instructions?.sections == ["guide"]) try Data( "---\ndescription: Guide.\n---\n# guide\n\nEdited instructions.\n".utf8 ).write(to: own) @@ -315,7 +319,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.swift")) 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 +345,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.swift")) == declaration) #expect(try Data(contentsOf: fixture.state("agents.resolved")) == lock) let applied = try fixture.success(arguments + ["--apply"]) #expect(applied.stdout.contains(recipients)) @@ -373,7 +377,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.swift")) let preview = try fixture.success(["instructions", "update", "--agent", "gemini-cli", "--json"]) .json() #expect(preview["changed"] as? Bool == true) @@ -397,7 +401,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.swift")) == before) try fixture.success(["instructions", "update", "--agent", "gemini-cli", "--apply"]) #expect(try String(contentsOf: claude, encoding: .utf8) == custom) #expect( @@ -536,7 +540,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.swift").path)) let listing = try fixture.success(["instructions", "list"]) #expect(listing.stdout == "No managed project instructions.\n") } @@ -625,20 +629,20 @@ 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.swift", 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, + .prompt( + name: "weekly", sections: [.section(name: "canonical-artifacts", source: "source")], + 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..d8090e9 --- /dev/null +++ b/Tests/CLITests/ManifestExecutableTests.swift @@ -0,0 +1,297 @@ +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 = """ + // agents-tools-version: 1.0 + import AgentsDescription + // Keep conditions, external references and runtime values symbolic. + let recipients: [Agent] = [.openCode, .codex] + let agents = Agents( + defaultAgents: recipients, + sources: [.source(name: "remote", url: "https://example.invalid/never-fetch.git")], + components: [ + .mcpServer( + name: "workspace", + transport: .stdio("never-run", environment: ["TOKEN": .secret("token")]), + condition: .when(scopes: [.user], platforms: [.linux]) + ), + .command(name: "review", description: "Review", prompt: .file("missing-prompt.md")), + ], + uses: [.group(name: "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.swift", 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", "languageVersion", "sourceDigest", "declaration", "locations", + "diagnostics", + ]) + #expect(dump["schemaVersion"] as? Int == 1 && dump["kind"] as? String == "manifest") + #expect(dump["languageVersion"] as? String == "1.0") + let declaration = try #require(dump["declaration"] as? [String: Any]) + #expect(declaration["defaultAgents"] as? [String] == ["codex", "opencode"]) + #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.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: [ + ("import AgentsDescription\nlet agents = Agents()", "manifest.version.missing"), + ( + "// agents-tools-version: 9.0\nimport AgentsDescription\nlet agents = Agents()", + "manifest.version.unsupported" + ), + ( + "// agents-tools-version: 1.0\nimport AgentsDescription\nlet agents = Agents(unknown: [])", + "manifest.call" + ), + ( + "// agents-tools-version: 1.0\nimport AgentsDescription\nlet agents = Agents(components: [", + "manifest.syntax" + ), + ( + "// agents-tools-version: 1.0\nimport AgentsDescription\nprint(\"executed\")\nlet agents = Agents()", + "manifest.syntax" + ), + ]) + func malformedManifestHasLocatedDiagnostics(source: String, code: String) throws { + let fixture = try CLIFixture() + try fixture.writeManifest(source) + let before = try Data(contentsOf: fixture.state("Agents.swift")) + let result = try fixture.run(["manifest", "dump", "--json"]) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect(result.stderr.contains("Agents.swift:") && result.stderr.contains("[\(code)]")) + #expect(result.stderr.hasSuffix("\n Fix the reported Agents.swift diagnostics and retry.\n")) + #expect(!result.stderr.contains("ManifestFailure(") && !result.stderr.contains("metrics:")) + #expect(try Data(contentsOf: fixture.state("Agents.swift")) == before) + #expect( + try FileManager.default.contentsOfDirectory(atPath: fixture.state("").path) == [ + "Agents.swift" + ]) + } + + @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.swift")) + #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.swift", 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.swift")) + #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.swift", 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.syntax") + && !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 = """ + // agents-tools-version: 1.0 + import AgentsDescription + + // Team-owned defaults. Keep this spelling and spacing. + let team: [Agent] = [.codex] + + """ + let manifest = + prefix + """ + let agents = Agents( + defaultAgents: team, + sources: [ + // Local collection, shared by skills and instructions. + .source(name: "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.swift", 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.swift", "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.swift", 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", + ]) + #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.swift", scope: scope), encoding: .utf8) + == "invalid manifest\n") + } +} diff --git a/Tests/CLITests/SkillOutputExecutableTests.swift b/Tests/CLITests/SkillOutputExecutableTests.swift index 36e56f9..dc90897 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,12 @@ 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( + """ + // agents-tools-version: 1.0 + import AgentsDescription + let agents = Agents() + """) 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")) @@ -166,14 +169,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..8d466ef 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(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..286aa3d 100644 --- a/Tests/CLITests/UpdateReportingTests.swift +++ b/Tests/CLITests/UpdateReportingTests.swift @@ -63,9 +63,12 @@ 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( + """ + // agents-tools-version: 1.0 + import AgentsDescription + let agents = Agents() + """) 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 +88,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: "[.claudeCode, .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) @@ -198,11 +201,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( + """ + // agents-tools-version: 1.0 + import AgentsDescription + let agents = Agents( + sources: [.source(name: "source", path: \(fixture.source.path.debugDescription))], + components: [ + .instructions( + sections: [], + chatGPT: [.prompt(name: "weekly", sections: [.section(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 +298,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.swift, agents.resolved, and recovery journal." ), ( .committed, "Update committed, but a later step failed.", @@ -307,14 +319,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..9cc26eb 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( + """ + // agents-tools-version: 1.0 + import AgentsDescription + let agents = Agents(sources: [ + .source(name: \(alias.debugDescription), path: \(fixture.source.path.debugDescription)), + .source(name: "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.swift", 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.swift", 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..6b20ccd 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( + """ + // agents-tools-version: 1.0 + import AgentsDescription + let agents = Agents(sources: [ + .source(name: \(id.debugDescription), path: \(fixture.source.path.debugDescription)), + .source(name: "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 { From 7d7517cd1cf8ede1c1ca82c2effef68c12e10e74 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:31:25 +0800 Subject: [PATCH 03/67] docs: describe macOS and Linux source support --- CONTRIBUTING.md | 5 +++-- Documentation/Reference/Release.md | 7 +++++-- README.md | 9 +++++---- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a6b8f3a..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, or Linux. 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/Reference/Release.md b/Documentation/Reference/Release.md index d53d90d..1502692 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 -On macOS, 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/README.md b/README.md index 8a199ab..1a16dab 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@

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

@@ -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 @@ -210,8 +210,9 @@ 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. +[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. From 80031757ab2bf8f4e2a074f49fd7469e907e0438 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:08:02 +0800 Subject: [PATCH 04/67] docs: align front ends with configuration application --- Documentation/Decisions/FrontEnds.md | 14 ++++++++++++-- Documentation/Decisions/ProductScope.md | 7 ++++++- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/Documentation/Decisions/FrontEnds.md b/Documentation/Decisions/FrontEnds.md index 1c27675..2acb78d 100644 --- a/Documentation/Decisions/FrontEnds.md +++ b/Documentation/Decisions/FrontEnds.md @@ -23,6 +23,15 @@ can disagree with each other and with any CLI. collections are named groups in the manifest. Moving a setup to another machine means syncing `Agents.swift` 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. @@ -32,7 +41,7 @@ can disagree with each other and with any CLI. - **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 a pending executable component. These + 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. @@ -69,5 +78,6 @@ can disagree with each other and with any CLI. - Accepted by the repository owner (showxu) on 2026-10-28. - Product scope: [Product Scope](ProductScope.md) -- Executable approval the GUI presents: [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 architecture: [Architecture](../Architecture/README.md) diff --git a/Documentation/Decisions/ProductScope.md b/Documentation/Decisions/ProductScope.md index 124471e..40570b1 100644 --- a/Documentation/Decisions/ProductScope.md +++ b/Documentation/Decisions/ProductScope.md @@ -29,6 +29,9 @@ with a macOS GUI. 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 @@ -55,5 +58,7 @@ with a macOS GUI. - Accepted by the repository owner (showxu) on 2026-10-28. - Front ends over core: [Front Ends](FrontEnds.md) -- Manifest, components and approval: [core decisions](https://github.com/agents-tools/core/tree/master/Documentation/Decisions) +- 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) From 3d4d378b242e1e6cf9fe0f0e33fc10e44862baab Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sat, 7 Nov 2026 00:54:57 +0800 Subject: [PATCH 05/67] build: adopt complete declaration support --- Package.resolved | 4 ++-- Package.swift | 2 +- Sources/CLI/InstructionCommands.swift | 2 +- Tests/CLITests/InstructionExecutableTests.swift | 5 +++-- Tests/CLITests/SourceSelectorTests.swift | 2 +- 5 files changed, 8 insertions(+), 7 deletions(-) diff --git a/Package.resolved b/Package.resolved index 4b96759..ae32444 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "e6051e2863ae30bcbb5dc71e47ff6e9fe7f381268509a8ad6c2debc0c02d0493", + "originHash" : "8662b9a0b0d7b9e94cc5cc6f34e86b018aff6cd8ca79826fa6551ceb871a0cd3", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "a2d734fb14cf2d93e7ddd8a6087d7c90453abea4" + "revision" : "994b82027d12edd3d7c63187a534150086993f7f" } }, { diff --git a/Package.swift b/Package.swift index 321f7b4..3b2d2f1 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "a2d734fb14cf2d93e7ddd8a6087d7c90453abea4"), + revision: "994b82027d12edd3d7c63187a534150086993f7f"), ], targets: [ .executableTarget( diff --git a/Sources/CLI/InstructionCommands.swift b/Sources/CLI/InstructionCommands.swift index c64682e..6f70a2e 100644 --- a/Sources/CLI/InstructionCommands.swift +++ b/Sources/CLI/InstructionCommands.swift @@ -196,7 +196,7 @@ struct RenderChatGPT: ParsableCommand { func run() throws { let declaration = try StateStore(scope: location.scope).loadDeclaration() - guard declaration.instructions?.chatgpt?[prompt] != nil else { + guard try declaration.instructions?.chatgpt?[prompt] != nil else { throw HumanOutputError.undeclaredPrompt(prompt) } let bytes = try InstructionOperations.renderChatGPT(prompt: prompt, scope: location.scope) diff --git a/Tests/CLITests/InstructionExecutableTests.swift b/Tests/CLITests/InstructionExecutableTests.swift index 71de2f2..9a193ed 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -134,7 +134,8 @@ struct InstructionExecutableTests { #expect(replaced.stdout.contains("+Original instructions")) try fixture.success(["instructions", "add", "source", "other"]) let declaration = try fixture.declaration() - #expect(declaration.instructions?.sections == ["source:canonical-artifacts", "source:other"]) + #expect( + try declaration.instructions?.sections == ["source:canonical-artifacts", "source:other"]) } @Test func editedTargetsFollowTheLockAndHandWrittenOnesNeedReplace() throws { @@ -279,7 +280,7 @@ struct InstructionExecutableTests { try String(contentsOf: target, encoding: .utf8) == generated(["# guide\n\nWrite the instructions here."])) let declaration = try fixture.declaration() - #expect(declaration.instructions?.sections == ["guide"]) + #expect(try declaration.instructions?.sections == ["guide"]) try Data( "---\ndescription: Guide.\n---\n# guide\n\nEdited instructions.\n".utf8 ).write(to: own) diff --git a/Tests/CLITests/SourceSelectorTests.swift b/Tests/CLITests/SourceSelectorTests.swift index 8d466ef..5f04d14 100644 --- a/Tests/CLITests/SourceSelectorTests.swift +++ b/Tests/CLITests/SourceSelectorTests.swift @@ -13,7 +13,7 @@ struct SourceSelectorTests { let declaration = try fixture.declaration() let source = try #require(declaration.sources["source"]) #expect(source.location == fixture.source.path && source.requirement == .branch("main")) - #expect(declaration.skills?["source"]?.select == .names(["demo"])) + #expect(try declaration.skills?["source"]?.select == .names(["demo"])) } @Test func instructionAddAcceptsRequirementsAndRejectsSkillSelectors() throws { From d317a0868465e8ac265c75a40c87d52ee5de2f55 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:26:50 +0800 Subject: [PATCH 06/67] feat(cli): support YAML configuration declarations --- .agent/agents.json | 17 -- .agent/agents.yaml | 13 ++ .gitignore | 2 +- Documentation/Decisions/FrontEnds.md | 6 +- Documentation/Decisions/ProductScope.md | 2 +- Documentation/README.md | 2 +- Documentation/Reference/CLI.md | 113 +++++++------ Documentation/Reference/ManifestDump.md | 28 ++-- Package.resolved | 12 +- Package.swift | 3 +- README.md | 10 +- Sources/CLI/ManifestCommands.swift | 6 +- Sources/CLI/Terminal.swift | 12 +- Tests/CLITests/CLIFixture.swift | 20 ++- Tests/CLITests/ExecutableTests.swift | 10 +- Tests/CLITests/HumanExecutableTests.swift | 13 +- .../CLITests/InstructionExecutableTests.swift | 30 ++-- Tests/CLITests/ManifestExecutableTests.swift | 151 ++++++++++-------- .../CLITests/SkillOutputExecutableTests.swift | 6 +- Tests/CLITests/UpdateReportingTests.swift | 30 ++-- Tests/CLITests/WatchExecutableTests.swift | 16 +- Tests/CLITests/WatchReportTests.swift | 12 +- 22 files changed, 262 insertions(+), 252 deletions(-) delete mode 100644 .agent/agents.json create mode 100644 .agent/agents.yaml 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.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/.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/Documentation/Decisions/FrontEnds.md b/Documentation/Decisions/FrontEnds.md index 2acb78d..10ede77 100644 --- a/Documentation/Decisions/FrontEnds.md +++ b/Documentation/Decisions/FrontEnds.md @@ -18,10 +18,10 @@ can disagree with each other and with any 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.swift`, the lock and +- **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.swift` and the lock and running + 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 @@ -48,7 +48,7 @@ can disagree with each other and with any CLI. - **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.swift`. + teaches agents and people to use `agents` and write `agents.yaml`. ## Consequences diff --git a/Documentation/Decisions/ProductScope.md b/Documentation/Decisions/ProductScope.md index 40570b1..564ff50 100644 --- a/Documentation/Decisions/ProductScope.md +++ b/Documentation/Decisions/ProductScope.md @@ -35,7 +35,7 @@ with a macOS GUI. - **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.swift`. + `agents.yaml`. ## Consequences diff --git a/Documentation/README.md b/Documentation/README.md index e338d40..60539e7 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -12,7 +12,7 @@ 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. -- [Manifest dump](Reference/ManifestDump.md): producer-owned language JSON contract +- [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 list, update previews, watch status and diffs, installation, and doctor. diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 1735441..256c921 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -108,16 +108,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 to the arguments of `.source` in `Agents.swift`: +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(from: "1.2.3")` | At least 1.2.3, below 1.3.0 | -| `--from 1.2.3 --to 1.8.0` | `"1.2.3"..<"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. @@ -141,7 +142,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.swift` +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 `. @@ -211,31 +212,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.swift`, using an existing +Declare named ChatGPT prompts in the scope's `agents.yaml`, using an existing source alias (here `rules`): -```swift -// agents-tools-version: 1.0 -import AgentsDescription - -let agents = Agents( - sources: [.source(name: "rules", path: "../team-rules")], - components: [ - .instructions( - sections: [.section(name: "canonical-artifacts", source: "rules")], - chatGPT: [ - .prompt( - name: "weekly", - sections: [.section(name: "canonical-artifacts", source: "rules")], - 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 ``` -Add the `.prompt` to the instructions component's `chatGPT` list. +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 @@ -252,17 +248,17 @@ 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.swift` under a shared lock and prints core's evaluated JSON bytes. +`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 evaluates the local static language without resolving external groups, -fetching sources or secrets, inspecting native files, or compiling or running -Swift code. 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. Syntax, type -and domain failures include path, line, UTF-8 byte column, severity and stable -diagnostic code on stderr; related locations follow when available. Invalid +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. @@ -341,7 +337,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.swift` 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 @@ -564,22 +560,25 @@ current directory and user scope uses HOME. | Scope | Declaration | Lock | Cache | | --- | --- | --- | --- | -| Project | `.agent/Agents.swift` | `.agent/agents.resolved` | `.agent/cache/` | -| User | `~/.agents/Agents.swift` | `~/.agents/agents.resolved` | `~/.agents/cache/` | - -A project commits its declaration and lock; the cache stays local. `Agents.swift` -uses the [manifest language](https://github.com/agents-tools/core/blob/a2d734fb14cf2d93e7ddd8a6087d7c90453abea4/Documentation/Reference/Manifest.md), -a statically evaluated Swift subset with a required version directive and -`import AgentsDescription`. Lifecycle commands use core's deployable subset. -Unsupported deployment constructs produce located diagnostics; dump accepts the -complete language. 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. The lock remains JSON, formatted by core when it changes. +| 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/bb5c1db909de58a2a4516e45a5b62b662700a14a/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.swift` is an error; restore the declaration before retrying. +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`, @@ -625,14 +624,14 @@ including ESC, CR, C1, and bidi controls, use visible escapes: ```text Error: No ChatGPT prompt named 'daily' is declared. - Declare it with .prompt in the instructions component of Agents.swift 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.swift` as -`.source(name: "missing", url: "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 @@ -677,8 +676,8 @@ 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 update, instruction -update and install reports, 1 for the others. Object keys are sorted. Arrays +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. @@ -697,7 +696,7 @@ 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 language object | +| `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` | diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 077d14a..7fb0d7b 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -1,19 +1,20 @@ # Manifest Dump Contract `agents manifest dump --json [--scope project|user]` exposes the manifest -language's evaluated JSON schema. The authoritative schema and byte contract -are core's [Evaluated JSON Dump](https://github.com/agents-tools/core/blob/a2d734fb14cf2d93e7ddd8a6087d7c90453abea4/Documentation/Reference/Manifest.md#evaluated-json-dump), -including its construction vocabulary and evolution rules. The CLI prints +format's JSON contract. The authoritative schema and byte contract +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/bb5c1db909de58a2a4516e45a5b62b662700a14a/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: 1`, `kind: "manifest"` and -`languageVersion: "1.0"`. It contains `sourceDigest`, `declaration`, `locations` -and `diagnostics`. These fields, their normalized values, discriminants, -ordering and defaults are owned by the linked language contract. Locations -use the stable document identity `manifest`, with UTF-8 byte offsets and -1-based line/byte-column coordinates. The source digest covers original bytes, -so comments can change digest and locations while declaration values stay equal. +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 @@ -23,5 +24,10 @@ 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 language object. +they do not describe declaration storage or this manifest object. diff --git a/Package.resolved b/Package.resolved index ae32444..ca3bc28 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "8662b9a0b0d7b9e94cc5cc6f34e86b018aff6cd8ca79826fa6551ceb871a0cd3", + "originHash" : "44dc224d35c138055b5bbfdf02f9b4ee6f277658acef1f85e7624173e50ce0d8", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "994b82027d12edd3d7c63187a534150086993f7f" + "revision" : "bb5c1db909de58a2a4516e45a5b62b662700a14a" } }, { @@ -55,12 +55,12 @@ } }, { - "identity" : "swift-syntax", + "identity" : "tree-sitter", "kind" : "remoteSourceControl", - "location" : "https://github.com/swiftlang/swift-syntax.git", + "location" : "https://github.com/tree-sitter/tree-sitter", "state" : { - "revision" : "050f1a346fbbac0ca2cfb15a95274f7bd1cf0ccf", - "version" : "604.0.0" + "revision" : "da6fe9beb4f7f67beb75914ca8e0d48ae48d6406", + "version" : "0.25.10" } }, { diff --git a/Package.swift b/Package.swift index 3b2d2f1..8925c6e 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "994b82027d12edd3d7c63187a534150086993f7f"), + revision: "bb5c1db909de58a2a4516e45a5b62b662700a14a"), ], targets: [ .executableTarget( @@ -27,7 +27,6 @@ let package = Package( name: "CLITests", dependencies: [ "CLI", .product(name: "AgentsManifest", package: "core"), - .product(name: "AgentsDescription", package: "core"), ]), ], swiftLanguageModes: [.v6] diff --git a/README.md b/README.md index 1a16dab..20c1c07 100644 --- a/README.md +++ b/README.md @@ -111,10 +111,10 @@ agents doctor --root /path/to/project-a /path/to/project-b --json agents manifest dump --json ``` -Declarations live in `.agent/Agents.swift` for project scope or -`~/.agents/Agents.swift` for user scope. The [manifest language](https://github.com/agents-tools/core/blob/a2d734fb14cf2d93e7ddd8a6087d7c90453abea4/Documentation/Reference/Manifest.md) -is a statically evaluated Swift subset. `agents manifest dump --json` prints the -local declaration and its source locations without resolving sources. +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/bb5c1db909de58a2a4516e45a5b62b662700a14a/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. @@ -133,7 +133,7 @@ remove, or update sets the recipients of the scope's entire section list. `agents instructions init ` creates `.agent/instructions/.md`, and `agents instructions export` maps locked targets to their sections. -Named ChatGPT prompts are declared in `Agents.swift` 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 diff --git a/Sources/CLI/ManifestCommands.swift b/Sources/CLI/ManifestCommands.swift index 0ca9095..1a84159 100644 --- a/Sources/CLI/ManifestCommands.swift +++ b/Sources/CLI/ManifestCommands.swift @@ -5,17 +5,17 @@ import Foundation struct Manifest: ParsableCommand { static let configuration = CommandConfiguration( - commandName: "manifest", abstract: "Inspect the scope's Agents.swift declaration.", + commandName: "manifest", abstract: "Inspect the scope's agents.yaml declaration.", subcommands: [DumpManifest.self]) } struct DumpManifest: ParsableCommand { static let configuration = CommandConfiguration( - commandName: "dump", abstract: "Print the local manifest's evaluated JSON and source locations." + commandName: "dump", abstract: "Print the local manifest's JSON and source locations." ) @OptionGroup var location: ScopeOptions - @Flag(help: "Print the manifest language JSON contract.") var json = false + @Flag(help: "Print the manifest JSON contract.") var json = false func validate() throws { if !json { throw ValidationError("manifest dump requires --json") } diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 5550931..95ad8be 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -86,7 +86,7 @@ enum Terminal { let action: String switch error { case is ManifestFailure: - action = "fix the reported Agents.swift diagnostics and retry" + 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" @@ -94,10 +94,10 @@ enum Terminal { action = "run 'agents install' in the same scope (add --scope user for user state) to finish recovery" case CoreError.missingDeclaration: - action = "restore Agents.swift from version control before retrying" + action = "restore agents.yaml from version control before retrying" case CoreError.notFound where command is DumpManifest: action = - "create Agents.swift in the selected scope before running 'agents manifest dump --json'" + "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:"): @@ -123,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.swift, 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: @@ -147,10 +147,10 @@ enum Terminal { "link only to files in the checkout being written, or name the file in text without a link" case HumanOutputError.undeclaredPrompt: action = - "declare it with .prompt in the instructions component of Agents.swift 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.swift 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'" default: diff --git a/Tests/CLITests/CLIFixture.swift b/Tests/CLITests/CLIFixture.swift index 20bbb87..56e3765 100644 --- a/Tests/CLITests/CLIFixture.swift +++ b/Tests/CLITests/CLIFixture.swift @@ -119,21 +119,25 @@ final class CLIFixture { } func writeManifest(_ source: String, scope: String = "project") throws { - let url = state("Agents.swift", scope: scope) + 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 = "[.claudeCode, .codex]") throws { + func declareSkills(mode: String = "link", agents: String = "[claude-code, codex]") throws { try writeManifest( """ - // agents-tools-version: 1.0 - import AgentsDescription - let agents = Agents( - sources: [.source(name: "source", path: \(source.path.debugDescription))], - components: [.skills(source: "source", select: ["pdf"], mode: .\(mode), agents: \(agents))] - ) + version: 1 + sources: + source: + path: \(source.path.debugDescription) + components: + - kind: skills + source: source + select: [pdf] + mode: \(mode) + agents: \(agents) """) } diff --git a/Tests/CLITests/ExecutableTests.swift b/Tests/CLITests/ExecutableTests.swift index 59c5b53..721f5ca 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.swift", 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]]) @@ -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.swift", 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.swift").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.swift").path)) + #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.yaml").path)) #expect( !FileManager.default.fileExists(atPath: fixture.project.appendingPathComponent(".agent").path) ) @@ -198,7 +198,7 @@ struct ExecutableTests { let cache = fixture.state("cache/content", scope: scope) try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: true) let files = [ - fixture.state("transaction.new", scope: scope), fixture.state("Agents.swift", 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( diff --git a/Tests/CLITests/HumanExecutableTests.swift b/Tests/CLITests/HumanExecutableTests.swift index 2b66b88..a125e16 100644 --- a/Tests/CLITests/HumanExecutableTests.swift +++ b/Tests/CLITests/HumanExecutableTests.swift @@ -9,9 +9,10 @@ struct HumanExecutableTests { let source = "file://localhost" + fixture.home.appendingPathComponent("missing.git").path try fixture.writeManifest( """ - // agents-tools-version: 1.0 - import AgentsDescription - let agents = Agents(sources: [.source(name: "missing", url: \(source.debugDescription))]) + version: 1 + sources: + missing: + url: \(source.debugDescription) """) let failure = try fixture.run(["skills", "add", "missing", "demo"]) #expect(failure.status == 1 && failure.stdout.isEmpty) @@ -200,7 +201,7 @@ struct HumanExecutableTests { try fixture.success([ "skills", "add", fixture.source.path, "pdf", "--mode", "edit", "--agent", "codex", ]) - try fixture.declareSkills(mode: "edit", agents: "[.cursor]") + 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( @@ -215,7 +216,7 @@ struct HumanExecutableTests { #expect(missing.status == 1 && missing.stdout.isEmpty) #expect( missing.stderr - == "Error: No ChatGPT prompt named 'daily' is declared.\n Declare it with .prompt in the instructions component of Agents.swift 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() @@ -232,7 +233,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.swift 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 9a193ed..3c6fec1 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -1,5 +1,4 @@ import AgentsCore -import AgentsDescription import AgentsInstructions import AgentsManifest import Foundation @@ -44,7 +43,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.swift", 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( @@ -60,7 +59,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.swift", 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) @@ -104,7 +103,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.swift").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") @@ -193,7 +192,7 @@ struct InstructionExecutableTests { try fixture.instruction() try fixture.commit() try fixture.success(["instructions", "add", fixture.source.path, "--agent", "codex"]) - let manifest = try Data(contentsOf: fixture.state("Agents.swift")) + 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("\" : ") }) @@ -208,7 +207,7 @@ struct InstructionExecutableTests { 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.swift")) == manifest) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == manifest) } } @@ -320,7 +319,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.swift")) + 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" @@ -346,7 +345,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.swift")) == 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)) @@ -378,7 +377,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.swift")) + 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) @@ -402,7 +401,7 @@ struct InstructionExecutableTests { let diffIndex = try #require(human.stdout.range(of: header)?.lowerBound) #expect(recipientsIndex < diffIndex) } - #expect(try Data(contentsOf: fixture.state("Agents.swift")) == 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( @@ -541,7 +540,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.swift").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") } @@ -631,7 +630,7 @@ extension CLIFixture { } func declarePrompt(scope: String = "project") throws { - let url = state("Agents.swift", 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 @@ -639,9 +638,10 @@ extension CLIFixture { let change = try document.preparing([ .upsertPrompt( node, - .prompt( - name: "weekly", sections: [.section(name: "canonical-artifacts", source: "source")], - append: "prompt-custom.md")) + 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( diff --git a/Tests/CLITests/ManifestExecutableTests.swift b/Tests/CLITests/ManifestExecutableTests.swift index d8090e9..e8c8fc0 100644 --- a/Tests/CLITests/ManifestExecutableTests.swift +++ b/Tests/CLITests/ManifestExecutableTests.swift @@ -8,28 +8,42 @@ struct ManifestExecutableTests { func dumpPrintsProducerBytesAndSymbolicValues(_ scope: String) throws { let fixture = try CLIFixture() let source = """ - // agents-tools-version: 1.0 - import AgentsDescription - // Keep conditions, external references and runtime values symbolic. - let recipients: [Agent] = [.openCode, .codex] - let agents = Agents( - defaultAgents: recipients, - sources: [.source(name: "remote", url: "https://example.invalid/never-fetch.git")], - components: [ - .mcpServer( - name: "workspace", - transport: .stdio("never-run", environment: ["TOKEN": .secret("token")]), - condition: .when(scopes: [.user], platforms: [.linux]) - ), - .command(name: "review", description: "Review", prompt: .file("missing-prompt.md")), - ], - uses: [.group(name: "external", source: "remote")] - ) + 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.swift", scope: scope) + let url = fixture.state("agents.yaml", scope: scope) let bytes = try Data(contentsOf: url) let before = try FileManager.default.subpathsOfDirectory( atPath: url.deletingLastPathComponent().path) @@ -40,18 +54,29 @@ struct ManifestExecutableTests { let dump = try result.json() #expect( Set(dump.keys) == [ - "schemaVersion", "kind", "languageVersion", "sourceDigest", "declaration", "locations", + "schemaVersion", "kind", "format", "manifestVersion", "sourceDigest", "declaration", + "locations", "diagnostics", ]) - #expect(dump["schemaVersion"] as? Int == 1 && dump["kind"] as? String == "manifest") - #expect(dump["languageVersion"] as? String == "1.0") + #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] == ["codex", "opencode"]) + #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")) @@ -64,37 +89,25 @@ struct ManifestExecutableTests { } @Test(arguments: [ - ("import AgentsDescription\nlet agents = Agents()", "manifest.version.missing"), - ( - "// agents-tools-version: 9.0\nimport AgentsDescription\nlet agents = Agents()", - "manifest.version.unsupported" - ), - ( - "// agents-tools-version: 1.0\nimport AgentsDescription\nlet agents = Agents(unknown: [])", - "manifest.call" - ), - ( - "// agents-tools-version: 1.0\nimport AgentsDescription\nlet agents = Agents(components: [", - "manifest.syntax" - ), - ( - "// agents-tools-version: 1.0\nimport AgentsDescription\nprint(\"executed\")\nlet agents = Agents()", - "manifest.syntax" - ), + ("{}", "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.swift")) + 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.swift:") && result.stderr.contains("[\(code)]")) - #expect(result.stderr.hasSuffix("\n Fix the reported Agents.swift diagnostics and retry.\n")) + #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.swift")) == before) + #expect(try Data(contentsOf: fixture.state("agents.yaml")) == before) #expect( try FileManager.default.contentsOfDirectory(atPath: fixture.state("").path) == [ - "Agents.swift" + "agents.yaml" ]) } @@ -105,7 +118,7 @@ struct ManifestExecutableTests { #expect(result.status == 1 && result.stdout.isEmpty) #expect( result.stderr.contains("Not found: declaration at") - && result.stderr.contains("Create Agents.swift")) + && result.stderr.contains("Create agents.yaml")) #expect(!FileManager.default.fileExists(atPath: fixture.state("", scope: scope).path)) } @@ -143,7 +156,7 @@ struct ManifestExecutableTests { "skills", "add", fixture.source.path, "--agent", "codex", "--scope", scope, ]) } - try FileManager.default.removeItem(at: fixture.state("Agents.swift", 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( @@ -156,7 +169,7 @@ struct ManifestExecutableTests { #expect(result.status == 1 && result.stdout.isEmpty) #expect( result.stderr.contains("Missing declaration at") - && result.stderr.contains("Restore Agents.swift")) + && result.stderr.contains("Restore agents.yaml")) #expect(try Data(contentsOf: url) == before) #expect( try FileManager.default.subpathsOfDirectory(atPath: fixture.state("", scope: scope).path) @@ -174,7 +187,7 @@ struct ManifestExecutableTests { try Data("incomplete lock".utf8).write(to: lock) for missing in [false, true] { if missing { - try FileManager.default.removeItem(at: fixture.state("Agents.swift", scope: scope)) + try FileManager.default.removeItem(at: fixture.state("agents.yaml", scope: scope)) } let paths = try FileManager.default.subpathsOfDirectory( atPath: fixture.state("", scope: scope).path @@ -188,7 +201,7 @@ struct ManifestExecutableTests { result.stderr.contains("Transaction recovery is pending") && !result.stderr.contains("Recovered")) #expect( - !result.stderr.contains("manifest.syntax") + !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)) @@ -206,25 +219,21 @@ struct ManifestExecutableTests { try fixture.instruction() try fixture.commit() let prefix = """ - // agents-tools-version: 1.0 - import AgentsDescription + version: 1 - // Team-owned defaults. Keep this spelling and spacing. - let team: [Agent] = [.codex] + # Team-owned defaults. Keep this spelling and spacing. + defaultAgents: [codex] """ let manifest = prefix + """ - let agents = Agents( - defaultAgents: team, - sources: [ - // Local collection, shared by skills and instructions. - .source(name: "rules", path: \(fixture.source.path.debugDescription)), - ], - components: [], // Deployment list. - watch: [] // Observations. - ) - // Keep the footer. + 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] @@ -236,14 +245,14 @@ struct ManifestExecutableTests { ] { try fixture.success(command + options) let text = try String( - contentsOf: fixture.state("Agents.swift", scope: scope), encoding: .utf8) + 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("# Local collection, shared by skills and instructions.")) #expect( - text.contains("// Deployment list.") && text.contains("// Observations.") - && text.hasSuffix("// Keep the footer.\n")) + text.contains("# Deployment list.") && text.contains("# Observations.") + && text.hasSuffix("# Keep the footer.\n")) } - let files = ["Agents.swift", "agents.resolved", "agents.watch"].map { + let files = ["agents.yaml", "agents.resolved", "agents.watch"].map { fixture.state($0, scope: scope) } let before = try files.map { try Data(contentsOf: $0) } @@ -261,8 +270,8 @@ struct ManifestExecutableTests { ] { try fixture.success(command + options) let text = try String( - contentsOf: fixture.state("Agents.swift", scope: scope), encoding: .utf8) - #expect(text.hasPrefix(prefix) && text.hasSuffix("// Keep the footer.\n")) + contentsOf: fixture.state("agents.yaml", scope: scope), encoding: .utf8) + #expect(text.hasPrefix(prefix) && text.hasSuffix("# Keep the footer.\n")) } } @@ -291,7 +300,7 @@ struct ManifestExecutableTests { && !dump.stderr.contains("run 'agents install'")) #expect(try Data(contentsOf: journal) == Data("{}".utf8)) #expect( - try String(contentsOf: fixture.state("Agents.swift", scope: scope), encoding: .utf8) + try String(contentsOf: fixture.state("agents.yaml", scope: scope), encoding: .utf8) == "invalid manifest\n") } } diff --git a/Tests/CLITests/SkillOutputExecutableTests.swift b/Tests/CLITests/SkillOutputExecutableTests.swift index dc90897..92506fa 100644 --- a/Tests/CLITests/SkillOutputExecutableTests.swift +++ b/Tests/CLITests/SkillOutputExecutableTests.swift @@ -86,7 +86,7 @@ struct SkillOutputExecutableTests { try fixture.skill("pdf") try fixture.commit() try fixture.success(["skills", "add", fixture.source.path, "pdf"]) - try fixture.declareSkills(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")) @@ -96,9 +96,7 @@ struct SkillOutputExecutableTests { "Removed pdf for claude-code.\nUpdated pdf for codex: \(revision) -> \(revision).\n")) try fixture.writeManifest( """ - // agents-tools-version: 1.0 - import AgentsDescription - let agents = Agents() + version: 1 """) let removed = try fixture.success(["skills", "update", "--apply"]).stdout #expect(removed.contains("--- a/pdf/SKILL.md\n+++ /dev/null\n")) diff --git a/Tests/CLITests/UpdateReportingTests.swift b/Tests/CLITests/UpdateReportingTests.swift index 286aa3d..33c0ad0 100644 --- a/Tests/CLITests/UpdateReportingTests.swift +++ b/Tests/CLITests/UpdateReportingTests.swift @@ -65,9 +65,7 @@ struct UpdateReportingTests { #expect(!repinned.contains("mode pdf/")) try fixture.writeManifest( """ - // agents-tools-version: 1.0 - import AgentsDescription - let agents = Agents() + version: 1 """) let removal = try fixture.success(command + ["--json"]).json() let removedSkill = try #require((removal["skills"] as? [[String: Any]])?.first) @@ -88,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 fixture.declareSkills(mode: "edit", agents: "[.claudeCode, .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) @@ -203,17 +201,17 @@ struct UpdateReportingTests { try fixture.declarePrompt() try fixture.writeManifest( """ - // agents-tools-version: 1.0 - import AgentsDescription - let agents = Agents( - sources: [.source(name: "source", path: \(fixture.source.path.debugDescription))], - components: [ - .instructions( - sections: [], - chatGPT: [.prompt(name: "weekly", sections: [.section(name: "canonical-artifacts", source: "source")], append: "prompt-custom.md")] - ) - ] - ) + 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")) @@ -298,7 +296,7 @@ struct UpdateReportingTests { @Test(arguments: [ ( UpdateApplyDisposition.unchanged, "Update failed; no update was applied.", - "Check the scope's Agents.swift, agents.resolved, and recovery journal." + "Check the scope's agents.yaml, agents.resolved, and recovery journal." ), ( .committed, "Update committed, but a later step failed.", diff --git a/Tests/CLITests/WatchExecutableTests.swift b/Tests/CLITests/WatchExecutableTests.swift index 9cc26eb..a70c99a 100644 --- a/Tests/CLITests/WatchExecutableTests.swift +++ b/Tests/CLITests/WatchExecutableTests.swift @@ -11,12 +11,12 @@ struct WatchExecutableTests { let alias = "example.invalid/rules" try fixture.writeManifest( """ - // agents-tools-version: 1.0 - import AgentsDescription - let agents = Agents(sources: [ - .source(name: \(alias.debugDescription), path: \(fixture.source.path.debugDescription)), - .source(name: "remote", url: "https://example.invalid/rules.git"), - ]) + 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 ")) @@ -94,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.swift", 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 = """ @@ -156,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.swift", 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) diff --git a/Tests/CLITests/WatchReportTests.swift b/Tests/CLITests/WatchReportTests.swift index 6b20ccd..97a0fa6 100644 --- a/Tests/CLITests/WatchReportTests.swift +++ b/Tests/CLITests/WatchReportTests.swift @@ -16,12 +16,12 @@ struct WatchReportTests { try fixture.commit() try fixture.writeManifest( """ - // agents-tools-version: 1.0 - import AgentsDescription - let agents = Agents(sources: [ - .source(name: \(id.debugDescription), path: \(fixture.source.path.debugDescription)), - .source(name: "remote", url: "https://example.invalid/rules.git"), - ]) + 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) From cd01f6739ea599ffac74735eaff1a504da3c9120 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:03:55 +0800 Subject: [PATCH 07/67] feat: add manifest schema and saved declaration checks --- Documentation/README.md | 2 + Documentation/Reference/CLI.md | 39 ++++- Documentation/Reference/Editors.md | 131 ++++++++++++++++ Documentation/Reference/ManifestDump.md | 2 +- Documentation/Reference/Release.md | 8 +- Package.resolved | 4 +- Package.swift | 2 +- README.md | 10 +- Sources/CLI/ManifestCommands.swift | 36 ++++- Sources/CLI/ManifestDiagnostics.swift | 42 ++++++ Sources/CLI/Terminal.swift | 2 + Tests/CLITests/ManifestEditorTests.swift | 184 +++++++++++++++++++++++ 12 files changed, 451 insertions(+), 11 deletions(-) create mode 100644 Documentation/Reference/Editors.md create mode 100644 Sources/CLI/ManifestDiagnostics.swift create mode 100644 Tests/CLITests/ManifestEditorTests.swift diff --git a/Documentation/README.md b/Documentation/README.md index 60539e7..dcaeddf 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -14,6 +14,8 @@ This directory indexes repository-native documentation for `agents-tools/cli`. state locations, and JSON contracts. - [Manifest dump](Reference/ManifestDump.md): producer-owned YAML manifest JSON contract exposed by `agents manifest dump --json`. +- [YAML editor setup](Reference/Editors.md): offline schema export and explicit + saved-file Core checks, with workspace-only settings and process tasks. - [JSON schemas](Reference/Schemas/): machine-readable schemas for list, update previews, watch status and diffs, installation, and doctor. - [Release checklist](Reference/Release.md): prepare and verify release commits, diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 256c921..43f0df7 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -27,6 +27,8 @@ agents watch diff [name] [--kind skill|instructions|artifact] [--json] agents watch seen [--revision ] [--scope project|user] agents watch remove [--scope project|user] agents manifest dump --json [--scope project|user] +agents manifest schema +agents manifest check [--scope project|user] agents install [--json] agents update [--apply | --json] agents doctor [--root …] [--json] @@ -262,6 +264,41 @@ code on stderr; related locations follow when available. Invalid arguments exit 64. See the [dump contract](ManifestDump.md) for encoding and schema ownership. +### Schema and Saved-File Checks + +`manifest schema` writes the exact bundled JSON schema bytes to stdout. It has +no scope or format flags and reads no declaration, state, configuration or +source. An installed executable must include its SwiftPM resource bundle. + +`manifest check [--scope project|user]` reads the saved declaration through +Core's read-only `loadManifest()`. It does not run recovery, resolve sources or +providers, inspect native files or start components. Clean success is silent; +returned warnings appear on stderr with exit 0. Core manifest errors appear on +stderr with exit 1 and empty stdout. Missing declarations, pending recovery and +I/O errors are command failures, not invented manifest diagnostics. Invalid +arguments exit 64. The project root is cwd; user scope uses HOME. + +Diagnostic lines have this stable form: + +```text +/absolute/path/agents.yaml:12: error [manifest.scalar]: invalid scalar (UTF-8 byte column 9) +/absolute/path/agents.yaml:18: info [manifest.scalar]: related location (UTF-8 byte column 3) +``` + +The severity and code of primary diagnostics come from Core; related spans use +`info` with that same code. Lines and UTF-8 byte columns are 1-based. Editor +matchers use the line, with byte columns retained in the message. Messages are +single-line escaped. Paths with control characters or line separators use a +non-clickable `Diagnostic at … (line …)` description, preserving the original +path visibly without identifying a different file. Other absolute paths retain +their exact spelling, including Unicode, spaces, colons and brackets. + +See [YAML editor setup](Editors.md) for offline local associations and an +explicit process task. Schema completion/hover/structural checks complement +saved-file Core validation; neither unsaved Core diagnostics nor exact scalar +semantics from JSON Schema alone are promised. Dump's byte/schema contract is +unchanged. + ## Watch `watch add ` subscribes without installing content and records the @@ -564,7 +601,7 @@ current directory and user scope uses HOME. | 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/bb5c1db909de58a2a4516e45a5b62b662700a14a/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/Editors.md b/Documentation/Reference/Editors.md new file mode 100644 index 0000000..c14bb46 --- /dev/null +++ b/Documentation/Reference/Editors.md @@ -0,0 +1,131 @@ +# YAML Editor Setup + +`agents manifest schema` exports the bundled schema offline. Standard YAML +completion, hover and structural validation use this same schema; saved-file +scalar, tag and domain diagnostics come from an explicit `agents manifest check`. +The checker does not inspect an unsaved editor buffer. Save and rerun the task +after each edit; old task results describe the last checked saved file. + +The examples below are workspace settings and process tasks for Cursor or VS +Code with Red Hat YAML. Actual editor/version verification is separate from CLI +validation. Choose your project root explicitly. Do not write these examples to +user-wide settings automatically. + +## Export and Associate the Schema + +Choose a local destination and re-export after upgrading the CLI: + +```sh +mkdir -p "$HOME/.local/share/agents" +agents manifest schema > "$HOME/.local/share/agents/agents.schema.json" +``` + +The schema is distributed with the executable; its `$id` is an identity, not an +instruction to download it. Replace the example absolute file URI below with +your exported file. In the selected project's `.vscode/settings.json`: + +```json +{ + "yaml.yamlVersion": "1.2", + "yaml.schemaStore.enable": false, + "yaml.validate": true, + "yaml.completion": true, + "yaml.hover": true, + "yaml.format.enable": false, + "editor.formatOnSave": false, + "yaml.schemas": { + "file:///Users/alice/.local/share/agents/agents.schema.json": [ + "/.agent/agents.yaml" + ] + } +} +``` + +Associate only the canonical declaration. For user scope, open the chosen +`~/.agents` directory as its own workspace and use `["/agents.yaml"]` for that +association. `agents.resolved` is tool-owned JSON and is not a declaration. + +The standard YAML schema provides field descriptions, examples, required fields, +union shapes and enums. It does not establish Core's exact scalar or domain +semantics: for example, mathematical JSON Schema integers cannot distinguish +`1` from `1.0`. Core also checks duplicate keys, allowed tags, integer bounds, +exact native decimal text, and references. Keep `!!float` values as authored; +do not add blanket custom tag allowances or auto-format/re-serialize them. + +## Check the Saved Declaration + +In that project's `.vscode/tasks.json`: + +```json +{ + "version": "2.0.0", + "tasks": [ + { + "label": "Check agents declaration", + "type": "process", + "command": "agents", + "args": ["manifest", "check", "--scope", "project"], + "options": {"cwd": "${workspaceFolder}"}, + "problemMatcher": { + "owner": "agents-manifest", + "source": "agents", + "fileLocation": "absolute", + "pattern": { + "regexp": "^(/.*):([0-9]+): (error|warning|info) \\[([^\\]]+)\\]: (.*)$", + "file": 1, + "line": 2, + "severity": 3, + "code": 4, + "message": 5 + } + } + } + ] +} +``` + +Run this task explicitly after saving. It reads `${workspaceFolder}/.agent/agents.yaml`; +it does not search parent directories or infer scope from the active tab. For a +multi-root workspace, select a root and give its task an explicit cwd. + +For the user-scope workspace, change the args to +`["manifest", "check", "--scope", "user"]` and use explicit task options such as: + +```json +{ + "cwd": "${workspaceFolder}", + "env": {"HOME": "/Users/alice"} +} +``` + +Replace `/Users/alice` with the intended home; user scope reads +`HOME/.agents/agents.yaml`, independently of cwd. It does not mean the workspace +folder is HOME. For isolated editor verification, use the isolated fixture home. + +The matcher links absolute paths and **lines only**. UTF-8 byte columns remain +in the message; they are not editor character columns. Related locations are +separate `info` lines carrying the original diagnostic code. Control characters +and line separators in messages are escaped. An unrepresentable path is shown +as `Diagnostic at … (line …)` and deliberately does not match a clickable file. +Scope, missing-file, recovery and I/O failures remain ordinary nonzero command +failures in the task terminal; they are not fabricated source diagnostics. + +No task applies fixes, runs recovery, resolves sources, reads secrets or executes +components. Success with warnings exits 0, a command or manifest error exits 1, +and invalid arguments exit 64. A clean declaration prints nothing. Check the +saved declaration again with `agents manifest dump --json` when you need Core's +complete readback; the checker itself does not print configuration values. + +## Distribution + +An installed `agents manifest schema` needs SwiftPM's AgentsManifest resource +bundle with the executable. Copying the executable alone is insufficient. The +verified macOS layout places the actual executable and +`core_AgentsManifest.bundle` together in `libexec`, with a `bin/agents` exec +launcher that invokes that real executable path. A binary symlink alone keeps +Foundation's bundle lookup under `bin` on the tested macOS runtime. + +The existing Homebrew formula installs only the executable; its schema-export +packaging update must be delivered and verified by the tap owner. Use a source +build with its resources until that update is available. The CLI does not +substitute an embedded second schema or fall back to a network service. diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 7fb0d7b..2767d6e 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/bb5c1db909de58a2a4516e45a5b62b662700a14a/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da/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. diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index 1502692..6106da4 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -138,7 +138,13 @@ release, or update it for later releases, in an `agents-tools/homebrew-tap` task worktree. Set the stable archive URL to the `agents` release and compute SHA-256 from the exact downloaded archive bytes. Keep HEAD as the development channel. Do not infer the archive digest from Git objects. The formula is named `agents` -and installs only the `agents` executable. +and must install the `agents` executable together with SwiftPM's AgentsManifest +resource bundle. On the verified macOS layout, keep the actual executable and +resource bundle in `libexec`, with a `bin/agents` exec launcher that invokes the +real executable path; a binary symlink alone looks for the bundle under `bin`. +The current tap's executable-only install needs a tap-owner packaging change before schema export is supported. +Validate `agents manifest schema` from outside the checkout with build-resource +fallback unavailable, and compare its bytes to the exact core schema resource. Match the formula's macOS requirement to the released CLI's minimum (macOS 15). diff --git a/Package.resolved b/Package.resolved index ca3bc28..548766b 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "44dc224d35c138055b5bbfdf02f9b4ee6f277658acef1f85e7624173e50ce0d8", + "originHash" : "a4735c1303f29d22b9b25bcbbcde3d50094a71909a3bbb2ab53a59363a1da4a5", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "bb5c1db909de58a2a4516e45a5b62b662700a14a" + "revision" : "953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da" } }, { diff --git a/Package.swift b/Package.swift index 8925c6e..2ebcc4b 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "bb5c1db909de58a2a4516e45a5b62b662700a14a"), + revision: "953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 20c1c07..c4c81cc 100644 --- a/README.md +++ b/README.md @@ -82,8 +82,10 @@ 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`. +An installed copy also needs SwiftPM's AgentsManifest resource bundle beside +the real executable for offline schema export; see +[editor setup](Documentation/Reference/Editors.md#distribution). ## Usage @@ -109,10 +111,12 @@ 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 manifest schema +agents manifest check ``` 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/bb5c1db909de58a2a4516e45a5b62b662700a14a/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da/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. diff --git a/Sources/CLI/ManifestCommands.swift b/Sources/CLI/ManifestCommands.swift index 1a84159..003cd45 100644 --- a/Sources/CLI/ManifestCommands.swift +++ b/Sources/CLI/ManifestCommands.swift @@ -5,8 +5,8 @@ import Foundation struct Manifest: ParsableCommand { static let configuration = CommandConfiguration( - commandName: "manifest", abstract: "Inspect the scope's agents.yaml declaration.", - subcommands: [DumpManifest.self]) + commandName: "manifest", abstract: "Inspect declarations and the bundled YAML schema.", + subcommands: [DumpManifest.self, SchemaManifest.self, CheckManifest.self]) } struct DumpManifest: ParsableCommand { @@ -30,3 +30,35 @@ struct DumpManifest: ParsableCommand { FileHandle.standardOutput.write(Data(bytes)) } } + +struct SchemaManifest: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "schema", abstract: "Print the bundled manifest JSON schema.") + + func run() throws { + FileHandle.standardOutput.write(Data(try ManifestSchemaResource.encodedJSON())) + } +} + +struct CheckManifest: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "check", abstract: "Check the saved declaration without resolving sources.") + + @OptionGroup var location: ScopeOptions + + func run() throws { + let store = StateStore(scope: location.scope) + do { + guard let document = try store.loadManifest() else { + throw CoreError.notFound("declaration at \(store.declarationURL.path)") + } + ManifestDiagnostics.write(document.diagnostics) + if document.diagnostics.contains(where: { $0.severity == .error }) { + throw ExitCode.failure + } + } catch let failure as ManifestFailure { + ManifestDiagnostics.write(failure.diagnostics) + throw ExitCode.failure + } + } +} diff --git a/Sources/CLI/ManifestDiagnostics.swift b/Sources/CLI/ManifestDiagnostics.swift new file mode 100644 index 0000000..091de1b --- /dev/null +++ b/Sources/CLI/ManifestDiagnostics.swift @@ -0,0 +1,42 @@ +import AgentsCore +import AgentsManifest +import Foundation + +/// Editor diagnostics link to lines; Core columns measure UTF-8 bytes, not editor characters. +enum ManifestDiagnostics { + static func write(_ diagnostics: [ManifestDiagnostic]) { + let text = diagnostics.map(render).joined() + FileHandle.standardError.write(Data(text.utf8)) + } + + static func render(_ diagnostic: ManifestDiagnostic) -> String { + let primary = location( + diagnostic.span, severity: diagnostic.severity.rawValue, code: diagnostic.code, + message: diagnostic.message) + let related = diagnostic.related.map { + location($0, severity: "info", code: diagnostic.code, message: "related location") + }.joined() + return primary + related + } + + private static func location( + _ span: SourceSpan, severity: String, code: String, message: String + ) -> String { + let path = span.document.rawValue + let visible = singleLine(path) + // Escaped file names describe the original path, but are not clickable file identities. + let prefix = + visible == path && path.hasPrefix("/") + ? "\(path):\(span.line): " + : "Diagnostic at \(visible) (line \(span.line)): " + return prefix + "\(severity) [\(singleLine(code))]: \(singleLine(message))" + + " (UTF-8 byte column \(span.column))\n" + } + + private static func singleLine(_ text: String) -> String { + Terminal.line(text) + .replacingOccurrences(of: "\t", with: "\\t") + .replacingOccurrences(of: "\u{2028}", with: "\\u{2028}") + .replacingOccurrences(of: "\u{2029}", with: "\\u{2029}") + } +} diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 95ad8be..4e28cf6 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -95,6 +95,8 @@ enum Terminal { "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 CheckManifest: + action = "create agents.yaml in the selected scope before running 'agents manifest check'" case CoreError.notFound where command is DumpManifest: action = "create agents.yaml in the selected scope before running 'agents manifest dump --json'" diff --git a/Tests/CLITests/ManifestEditorTests.swift b/Tests/CLITests/ManifestEditorTests.swift new file mode 100644 index 0000000..e63c9f4 --- /dev/null +++ b/Tests/CLITests/ManifestEditorTests.swift @@ -0,0 +1,184 @@ +import AgentsCore +import AgentsManifest +import Foundation +import Testing + +@testable import CLI + +struct ManifestEditorTests { + @Test func schemaIsExactAndIndependentOfScopeState() throws { + let fixture = try CLIFixture() + for scope in ["project", "user"] { + try fixture.writeManifest("invalid manifest", scope: scope) + try Data("pending".utf8).write(to: fixture.state("transaction.new", scope: scope)) + } + let before = try inventory(fixture.root) + let result = try fixture.success(["manifest", "schema"]) + #expect(Data(result.stdout.utf8) == Data(try ManifestSchemaResource.encodedJSON())) + #expect(try inventory(fixture.root) == before) + } + + @Test(arguments: ["project", "user"]) + func checkIsReadOnlyAndLeavesDumpUnchanged(_ scope: String) throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + """ + version: 1 + # The checker must not fetch sources or evaluate deployment conditions. + sources: + remote: {url: https://example.invalid/never-fetch.git} + components: + - {kind: command, name: review, description: Review, prompt: {file: {path: missing.md}}} + uses: [{source: remote, group: external}] + """, scope: scope) + let arguments = ["--scope", scope] + let dump = try fixture.success(["manifest", "dump", "--json"] + arguments).stdout + let before = try inventory(fixture.root) + let result = try fixture.success(["manifest", "check"] + arguments) + #expect(result.stdout.isEmpty) + #expect(try inventory(fixture.root) == before) + #expect(try fixture.success(["manifest", "dump", "--json"] + arguments).stdout == dump) + } + + @Test(arguments: ["project", "user"]) + func warningsAreSuccessfulAndLocated(_ scope: String) throws { + let fixture = try CLIFixture() + try fixture.writeManifest( + "version: 1\nsources:\n rules: {url: github.com/example/rules}\n", scope: scope) + let before = try inventory(fixture.root) + let result = try fixture.run(["manifest", "check", "--scope", scope]) + #expect(result.status == 0 && result.stdout.isEmpty) + #expect( + result.stderr.contains( + "\(fixture.state("agents.yaml", scope: scope).path):3: warning [manifest.domain]:")) + #expect(result.stderr.contains("(UTF-8 byte column ")) + #expect(!result.stderr.contains("Error:") && !result.stderr.contains("Fix the reported")) + #expect(try inventory(fixture.root) == before) + } + + @Test(arguments: ["project", "user"]) + func errorsUseLineCoordinatesWithByteColumnsInMessages(_ scope: String) throws { + let fixture = try CLIFixture() + let prefix = "sources: {'🙂e\u{301}': {path: .}, " + try fixture.writeManifest( + "\u{FEFF}version: 1\r\n# Saved document\r\n" + prefix + + #"same: {path: .}, "\u0073ame": {path: .}}"#, scope: scope) + let before = try inventory(fixture.root) + let result = try fixture.run(["manifest", "check", "--scope", scope]) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect( + result.stderr.hasPrefix( + "\(fixture.state("agents.yaml", scope: scope).path):3: error [manifest.key.duplicate]:")) + #expect(result.stderr.hasSuffix("(UTF-8 byte column \(prefix.utf8.count + 1))\n")) + #expect(!result.stderr.contains("related location") && !result.stderr.contains("Error:")) + #expect(try inventory(fixture.root) == before) + } + + @Test(arguments: ["project", "user"]) + func missingPendingAndIOFailuresAreCommandFailures(_ scope: String) throws { + let fixture = try CLIFixture() + let arguments = ["manifest", "check", "--scope", scope] + let missing = try fixture.run(arguments) + #expect(missing.status == 1 && missing.stdout.isEmpty) + #expect( + missing.stderr.contains("Not found: declaration at") + && missing.stderr.contains("Create agents.yaml")) + #expect(!missing.stderr.contains("[manifest.")) + #expect(!FileManager.default.fileExists(atPath: fixture.state("", scope: scope).path)) + try fixture.writeManifest("invalid YAML", scope: scope) + try Data("pending".utf8).write(to: fixture.state("transaction.new", scope: scope)) + let before = try inventory(fixture.root) + let pending = try fixture.run(arguments) + #expect(pending.status == 1 && pending.stdout.isEmpty) + #expect( + pending.stderr.contains("Transaction recovery is pending") + && !pending.stderr.contains("[manifest.")) + #expect(try inventory(fixture.root) == before) + try FileManager.default.removeItem(at: fixture.state("transaction.new", scope: scope)) + try FileManager.default.removeItem(at: fixture.state("agents.yaml", scope: scope)) + try FileManager.default.createDirectory( + at: fixture.state("agents.yaml", scope: scope), withIntermediateDirectories: true) + let ioBefore = try inventory(fixture.root) + let io = try fixture.run(arguments) + #expect(io.status == 1 && io.stdout.isEmpty && !io.stderr.contains("[manifest.")) + #expect(try inventory(fixture.root) == ioBefore) + } + + @Test(arguments: ["rules:12 [中文]🙂", "rules\nline", "rules\tname"]) + func specialPathsAndMessagesRemainSingleLine(_ name: String) throws { + let fixture = try CLIFixture() + let project = fixture.project.appendingPathComponent(name) + let state = project.appendingPathComponent(".agent") + try FileManager.default.createDirectory(at: state, withIntermediateDirectories: true) + try Data("version: 1\n\"unknown\\nfield\\u2028\": []\n".utf8).write( + to: state.appendingPathComponent("agents.yaml")) + let before = try inventory(fixture.root) + let result = try fixture.run(["manifest", "check"], directory: project) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect(result.stderr.filter { $0 == "\n" }.count == 1) + #expect(result.stderr.contains("unknown\\nfield\\u{2028}")) + if name.contains("\n") || name.contains("\t") { + #expect(result.stderr.hasPrefix("Diagnostic at ")) + } else { + #expect( + result.stderr.hasPrefix( + state.appendingPathComponent("agents.yaml").path + ":2: error [manifest.schema]:")) + } + #expect(try inventory(fixture.root) == before) + } + + @Test(arguments: [ + ["manifest", "schema", "--json"], ["manifest", "schema", "--scope", "project"], + ["manifest", "schema", "file"], ["manifest", "check", "--json"], + ["manifest", "check", "--scope", "global"], ["manifest", "check", "file"], + ]) + func usageFailures(_ arguments: [String]) throws { + let fixture = try CLIFixture() + let before = try inventory(fixture.root) + let result = try fixture.run(arguments) + #expect(result.status == 64 && result.stdout.isEmpty) + #expect(result.stderr.contains("Run 'agents --help' for usage.")) + #expect(try inventory(fixture.root) == before) + } + + @Test func diagnosticLinesSanitizeMessagesAndAvoidFalsePathLinks() { + let diagnostic = ManifestDiagnostic( + code: "manifest.domain", message: "bad\r\nvalue\t\u{2028}\u{2029}\u{1B}", + span: SourceSpan( + document: DocumentIdentity("/project:a [b]/agents.yaml"), start: 0, end: 1, line: 3, + column: 9), + related: [ + SourceSpan( + document: DocumentIdentity("/other/agents.yaml"), start: 0, end: 1, line: 5, column: 7) + ]) + #expect( + ManifestDiagnostics.render(diagnostic) + == "/project:a [b]/agents.yaml:3: error [manifest.domain]: bad\\r\\nvalue\\t\\u{2028}\\u{2029}\\x1b (UTF-8 byte column 9)\n/other/agents.yaml:5: info [manifest.domain]: related location (UTF-8 byte column 7)\n" + ) + let unusual = ManifestDiagnostic( + code: "manifest.schema", message: "invalid", + span: SourceSpan( + document: DocumentIdentity("/project\nname/agents.yaml"), start: 0, end: 1, line: 2, + column: 1)) + #expect( + ManifestDiagnostics.render(unusual).hasPrefix( + "Diagnostic at /project\\nname/agents.yaml (line 2): error [manifest.schema]:")) + } + + private func inventory(_ root: URL) throws -> [String: String] { + let manager = FileManager.default + // CLIFixture owns these two root-level output captures; every CLI state path stays included. + return try Dictionary( + uniqueKeysWithValues: manager.subpathsOfDirectory(atPath: root.path).filter { + $0 != "stdout" && $0 != "stderr" + }.map { path in + let url = root.appendingPathComponent(path) + let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + if values.isSymbolicLink == true { + return (path, "link:" + (try manager.destinationOfSymbolicLink(atPath: url.path))) + } + if values.isDirectory == true { return (path, "directory") } + return (path, "file:" + (try Data(contentsOf: url)).base64EncodedString()) + }) + } +} From 361789edabcfcb9bb4e158a8f0a0761770ac48d9 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 11:58:52 +0800 Subject: [PATCH 08/67] docs: clarify editor setup and resource installation --- Documentation/Reference/Editors.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/Documentation/Reference/Editors.md b/Documentation/Reference/Editors.md index c14bb46..ebeac9d 100644 --- a/Documentation/Reference/Editors.md +++ b/Documentation/Reference/Editors.md @@ -7,9 +7,8 @@ The checker does not inspect an unsaved editor buffer. Save and rerun the task after each edit; old task results describe the last checked saved file. The examples below are workspace settings and process tasks for Cursor or VS -Code with Red Hat YAML. Actual editor/version verification is separate from CLI -validation. Choose your project root explicitly. Do not write these examples to -user-wide settings automatically. +Code with Red Hat YAML. Choose your project root explicitly. Do not write these +examples to user-wide settings automatically. ## Export and Associate the Schema @@ -100,7 +99,7 @@ For the user-scope workspace, change the args to Replace `/Users/alice` with the intended home; user scope reads `HOME/.agents/agents.yaml`, independently of cwd. It does not mean the workspace -folder is HOME. For isolated editor verification, use the isolated fixture home. +folder is HOME. The matcher links absolute paths and **lines only**. UTF-8 byte columns remain in the message; they are not editor character columns. Related locations are @@ -125,7 +124,7 @@ verified macOS layout places the actual executable and launcher that invokes that real executable path. A binary symlink alone keeps Foundation's bundle lookup under `bin` on the tested macOS runtime. -The existing Homebrew formula installs only the executable; its schema-export -packaging update must be delivered and verified by the tap owner. Use a source -build with its resources until that update is available. The CLI does not +The current Homebrew formula installs only the executable. For schema export, +run the source-built executable from its build directory with its resource +bundle, or manually install both using the layout above. The CLI does not substitute an embedded second schema or fall back to a network service. From cc21d7b44179855b674dce397e1f9c349f4122ad Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:32:50 +0800 Subject: [PATCH 09/67] refactor: focus manifest commands on configuration inspection --- Documentation/README.md | 2 - Documentation/Reference/CLI.md | 37 ----- Documentation/Reference/Editors.md | 130 ---------------- Documentation/Reference/Release.md | 8 +- README.md | 5 - Sources/CLI/ManifestCommands.swift | 36 +---- Sources/CLI/ManifestDiagnostics.swift | 42 ------ Sources/CLI/Terminal.swift | 2 - Tests/CLITests/ManifestEditorTests.swift | 184 ----------------------- 9 files changed, 3 insertions(+), 443 deletions(-) delete mode 100644 Documentation/Reference/Editors.md delete mode 100644 Sources/CLI/ManifestDiagnostics.swift delete mode 100644 Tests/CLITests/ManifestEditorTests.swift diff --git a/Documentation/README.md b/Documentation/README.md index dcaeddf..60539e7 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -14,8 +14,6 @@ This directory indexes repository-native documentation for `agents-tools/cli`. state locations, and JSON contracts. - [Manifest dump](Reference/ManifestDump.md): producer-owned YAML manifest JSON contract exposed by `agents manifest dump --json`. -- [YAML editor setup](Reference/Editors.md): offline schema export and explicit - saved-file Core checks, with workspace-only settings and process tasks. - [JSON schemas](Reference/Schemas/): machine-readable schemas for list, update previews, watch status and diffs, installation, and doctor. - [Release checklist](Reference/Release.md): prepare and verify release commits, diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 43f0df7..19adfd7 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -27,8 +27,6 @@ agents watch diff [name] [--kind skill|instructions|artifact] [--json] agents watch seen [--revision ] [--scope project|user] agents watch remove [--scope project|user] agents manifest dump --json [--scope project|user] -agents manifest schema -agents manifest check [--scope project|user] agents install [--json] agents update [--apply | --json] agents doctor [--root …] [--json] @@ -264,41 +262,6 @@ code on stderr; related locations follow when available. Invalid arguments exit 64. See the [dump contract](ManifestDump.md) for encoding and schema ownership. -### Schema and Saved-File Checks - -`manifest schema` writes the exact bundled JSON schema bytes to stdout. It has -no scope or format flags and reads no declaration, state, configuration or -source. An installed executable must include its SwiftPM resource bundle. - -`manifest check [--scope project|user]` reads the saved declaration through -Core's read-only `loadManifest()`. It does not run recovery, resolve sources or -providers, inspect native files or start components. Clean success is silent; -returned warnings appear on stderr with exit 0. Core manifest errors appear on -stderr with exit 1 and empty stdout. Missing declarations, pending recovery and -I/O errors are command failures, not invented manifest diagnostics. Invalid -arguments exit 64. The project root is cwd; user scope uses HOME. - -Diagnostic lines have this stable form: - -```text -/absolute/path/agents.yaml:12: error [manifest.scalar]: invalid scalar (UTF-8 byte column 9) -/absolute/path/agents.yaml:18: info [manifest.scalar]: related location (UTF-8 byte column 3) -``` - -The severity and code of primary diagnostics come from Core; related spans use -`info` with that same code. Lines and UTF-8 byte columns are 1-based. Editor -matchers use the line, with byte columns retained in the message. Messages are -single-line escaped. Paths with control characters or line separators use a -non-clickable `Diagnostic at … (line …)` description, preserving the original -path visibly without identifying a different file. Other absolute paths retain -their exact spelling, including Unicode, spaces, colons and brackets. - -See [YAML editor setup](Editors.md) for offline local associations and an -explicit process task. Schema completion/hover/structural checks complement -saved-file Core validation; neither unsaved Core diagnostics nor exact scalar -semantics from JSON Schema alone are promised. Dump's byte/schema contract is -unchanged. - ## Watch `watch add ` subscribes without installing content and records the diff --git a/Documentation/Reference/Editors.md b/Documentation/Reference/Editors.md deleted file mode 100644 index ebeac9d..0000000 --- a/Documentation/Reference/Editors.md +++ /dev/null @@ -1,130 +0,0 @@ -# YAML Editor Setup - -`agents manifest schema` exports the bundled schema offline. Standard YAML -completion, hover and structural validation use this same schema; saved-file -scalar, tag and domain diagnostics come from an explicit `agents manifest check`. -The checker does not inspect an unsaved editor buffer. Save and rerun the task -after each edit; old task results describe the last checked saved file. - -The examples below are workspace settings and process tasks for Cursor or VS -Code with Red Hat YAML. Choose your project root explicitly. Do not write these -examples to user-wide settings automatically. - -## Export and Associate the Schema - -Choose a local destination and re-export after upgrading the CLI: - -```sh -mkdir -p "$HOME/.local/share/agents" -agents manifest schema > "$HOME/.local/share/agents/agents.schema.json" -``` - -The schema is distributed with the executable; its `$id` is an identity, not an -instruction to download it. Replace the example absolute file URI below with -your exported file. In the selected project's `.vscode/settings.json`: - -```json -{ - "yaml.yamlVersion": "1.2", - "yaml.schemaStore.enable": false, - "yaml.validate": true, - "yaml.completion": true, - "yaml.hover": true, - "yaml.format.enable": false, - "editor.formatOnSave": false, - "yaml.schemas": { - "file:///Users/alice/.local/share/agents/agents.schema.json": [ - "/.agent/agents.yaml" - ] - } -} -``` - -Associate only the canonical declaration. For user scope, open the chosen -`~/.agents` directory as its own workspace and use `["/agents.yaml"]` for that -association. `agents.resolved` is tool-owned JSON and is not a declaration. - -The standard YAML schema provides field descriptions, examples, required fields, -union shapes and enums. It does not establish Core's exact scalar or domain -semantics: for example, mathematical JSON Schema integers cannot distinguish -`1` from `1.0`. Core also checks duplicate keys, allowed tags, integer bounds, -exact native decimal text, and references. Keep `!!float` values as authored; -do not add blanket custom tag allowances or auto-format/re-serialize them. - -## Check the Saved Declaration - -In that project's `.vscode/tasks.json`: - -```json -{ - "version": "2.0.0", - "tasks": [ - { - "label": "Check agents declaration", - "type": "process", - "command": "agents", - "args": ["manifest", "check", "--scope", "project"], - "options": {"cwd": "${workspaceFolder}"}, - "problemMatcher": { - "owner": "agents-manifest", - "source": "agents", - "fileLocation": "absolute", - "pattern": { - "regexp": "^(/.*):([0-9]+): (error|warning|info) \\[([^\\]]+)\\]: (.*)$", - "file": 1, - "line": 2, - "severity": 3, - "code": 4, - "message": 5 - } - } - } - ] -} -``` - -Run this task explicitly after saving. It reads `${workspaceFolder}/.agent/agents.yaml`; -it does not search parent directories or infer scope from the active tab. For a -multi-root workspace, select a root and give its task an explicit cwd. - -For the user-scope workspace, change the args to -`["manifest", "check", "--scope", "user"]` and use explicit task options such as: - -```json -{ - "cwd": "${workspaceFolder}", - "env": {"HOME": "/Users/alice"} -} -``` - -Replace `/Users/alice` with the intended home; user scope reads -`HOME/.agents/agents.yaml`, independently of cwd. It does not mean the workspace -folder is HOME. - -The matcher links absolute paths and **lines only**. UTF-8 byte columns remain -in the message; they are not editor character columns. Related locations are -separate `info` lines carrying the original diagnostic code. Control characters -and line separators in messages are escaped. An unrepresentable path is shown -as `Diagnostic at … (line …)` and deliberately does not match a clickable file. -Scope, missing-file, recovery and I/O failures remain ordinary nonzero command -failures in the task terminal; they are not fabricated source diagnostics. - -No task applies fixes, runs recovery, resolves sources, reads secrets or executes -components. Success with warnings exits 0, a command or manifest error exits 1, -and invalid arguments exit 64. A clean declaration prints nothing. Check the -saved declaration again with `agents manifest dump --json` when you need Core's -complete readback; the checker itself does not print configuration values. - -## Distribution - -An installed `agents manifest schema` needs SwiftPM's AgentsManifest resource -bundle with the executable. Copying the executable alone is insufficient. The -verified macOS layout places the actual executable and -`core_AgentsManifest.bundle` together in `libexec`, with a `bin/agents` exec -launcher that invokes that real executable path. A binary symlink alone keeps -Foundation's bundle lookup under `bin` on the tested macOS runtime. - -The current Homebrew formula installs only the executable. For schema export, -run the source-built executable from its build directory with its resource -bundle, or manually install both using the layout above. The CLI does not -substitute an embedded second schema or fall back to a network service. diff --git a/Documentation/Reference/Release.md b/Documentation/Reference/Release.md index 6106da4..1502692 100644 --- a/Documentation/Reference/Release.md +++ b/Documentation/Reference/Release.md @@ -138,13 +138,7 @@ release, or update it for later releases, in an `agents-tools/homebrew-tap` task worktree. Set the stable archive URL to the `agents` release and compute SHA-256 from the exact downloaded archive bytes. Keep HEAD as the development channel. Do not infer the archive digest from Git objects. The formula is named `agents` -and must install the `agents` executable together with SwiftPM's AgentsManifest -resource bundle. On the verified macOS layout, keep the actual executable and -resource bundle in `libexec`, with a `bin/agents` exec launcher that invokes the -real executable path; a binary symlink alone looks for the bundle under `bin`. -The current tap's executable-only install needs a tap-owner packaging change before schema export is supported. -Validate `agents manifest schema` from outside the checkout with build-resource -fallback unavailable, and compare its bytes to the exact core schema resource. +and installs only the `agents` executable. Match the formula's macOS requirement to the released CLI's minimum (macOS 15). diff --git a/README.md b/README.md index c4c81cc..66688cd 100644 --- a/README.md +++ b/README.md @@ -83,9 +83,6 @@ swift build -c release ``` To run from this checkout, use `.build/release/agents` or `swift run agents`. -An installed copy also needs SwiftPM's AgentsManifest resource bundle beside -the real executable for offline schema export; see -[editor setup](Documentation/Reference/Editors.md#distribution). ## Usage @@ -111,8 +108,6 @@ 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 manifest schema -agents manifest check ``` Declarations live in `.agent/agents.yaml` for project scope or diff --git a/Sources/CLI/ManifestCommands.swift b/Sources/CLI/ManifestCommands.swift index 003cd45..a179dae 100644 --- a/Sources/CLI/ManifestCommands.swift +++ b/Sources/CLI/ManifestCommands.swift @@ -5,8 +5,8 @@ import Foundation struct Manifest: ParsableCommand { static let configuration = CommandConfiguration( - commandName: "manifest", abstract: "Inspect declarations and the bundled YAML schema.", - subcommands: [DumpManifest.self, SchemaManifest.self, CheckManifest.self]) + commandName: "manifest", abstract: "Inspect local declarations.", + subcommands: [DumpManifest.self]) } struct DumpManifest: ParsableCommand { @@ -30,35 +30,3 @@ struct DumpManifest: ParsableCommand { FileHandle.standardOutput.write(Data(bytes)) } } - -struct SchemaManifest: ParsableCommand { - static let configuration = CommandConfiguration( - commandName: "schema", abstract: "Print the bundled manifest JSON schema.") - - func run() throws { - FileHandle.standardOutput.write(Data(try ManifestSchemaResource.encodedJSON())) - } -} - -struct CheckManifest: ParsableCommand { - static let configuration = CommandConfiguration( - commandName: "check", abstract: "Check the saved declaration without resolving sources.") - - @OptionGroup var location: ScopeOptions - - func run() throws { - let store = StateStore(scope: location.scope) - do { - guard let document = try store.loadManifest() else { - throw CoreError.notFound("declaration at \(store.declarationURL.path)") - } - ManifestDiagnostics.write(document.diagnostics) - if document.diagnostics.contains(where: { $0.severity == .error }) { - throw ExitCode.failure - } - } catch let failure as ManifestFailure { - ManifestDiagnostics.write(failure.diagnostics) - throw ExitCode.failure - } - } -} diff --git a/Sources/CLI/ManifestDiagnostics.swift b/Sources/CLI/ManifestDiagnostics.swift deleted file mode 100644 index 091de1b..0000000 --- a/Sources/CLI/ManifestDiagnostics.swift +++ /dev/null @@ -1,42 +0,0 @@ -import AgentsCore -import AgentsManifest -import Foundation - -/// Editor diagnostics link to lines; Core columns measure UTF-8 bytes, not editor characters. -enum ManifestDiagnostics { - static func write(_ diagnostics: [ManifestDiagnostic]) { - let text = diagnostics.map(render).joined() - FileHandle.standardError.write(Data(text.utf8)) - } - - static func render(_ diagnostic: ManifestDiagnostic) -> String { - let primary = location( - diagnostic.span, severity: diagnostic.severity.rawValue, code: diagnostic.code, - message: diagnostic.message) - let related = diagnostic.related.map { - location($0, severity: "info", code: diagnostic.code, message: "related location") - }.joined() - return primary + related - } - - private static func location( - _ span: SourceSpan, severity: String, code: String, message: String - ) -> String { - let path = span.document.rawValue - let visible = singleLine(path) - // Escaped file names describe the original path, but are not clickable file identities. - let prefix = - visible == path && path.hasPrefix("/") - ? "\(path):\(span.line): " - : "Diagnostic at \(visible) (line \(span.line)): " - return prefix + "\(severity) [\(singleLine(code))]: \(singleLine(message))" - + " (UTF-8 byte column \(span.column))\n" - } - - private static func singleLine(_ text: String) -> String { - Terminal.line(text) - .replacingOccurrences(of: "\t", with: "\\t") - .replacingOccurrences(of: "\u{2028}", with: "\\u{2028}") - .replacingOccurrences(of: "\u{2029}", with: "\\u{2029}") - } -} diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 4e28cf6..95ad8be 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -95,8 +95,6 @@ enum Terminal { "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 CheckManifest: - action = "create agents.yaml in the selected scope before running 'agents manifest check'" case CoreError.notFound where command is DumpManifest: action = "create agents.yaml in the selected scope before running 'agents manifest dump --json'" diff --git a/Tests/CLITests/ManifestEditorTests.swift b/Tests/CLITests/ManifestEditorTests.swift deleted file mode 100644 index e63c9f4..0000000 --- a/Tests/CLITests/ManifestEditorTests.swift +++ /dev/null @@ -1,184 +0,0 @@ -import AgentsCore -import AgentsManifest -import Foundation -import Testing - -@testable import CLI - -struct ManifestEditorTests { - @Test func schemaIsExactAndIndependentOfScopeState() throws { - let fixture = try CLIFixture() - for scope in ["project", "user"] { - try fixture.writeManifest("invalid manifest", scope: scope) - try Data("pending".utf8).write(to: fixture.state("transaction.new", scope: scope)) - } - let before = try inventory(fixture.root) - let result = try fixture.success(["manifest", "schema"]) - #expect(Data(result.stdout.utf8) == Data(try ManifestSchemaResource.encodedJSON())) - #expect(try inventory(fixture.root) == before) - } - - @Test(arguments: ["project", "user"]) - func checkIsReadOnlyAndLeavesDumpUnchanged(_ scope: String) throws { - let fixture = try CLIFixture() - try fixture.writeManifest( - """ - version: 1 - # The checker must not fetch sources or evaluate deployment conditions. - sources: - remote: {url: https://example.invalid/never-fetch.git} - components: - - {kind: command, name: review, description: Review, prompt: {file: {path: missing.md}}} - uses: [{source: remote, group: external}] - """, scope: scope) - let arguments = ["--scope", scope] - let dump = try fixture.success(["manifest", "dump", "--json"] + arguments).stdout - let before = try inventory(fixture.root) - let result = try fixture.success(["manifest", "check"] + arguments) - #expect(result.stdout.isEmpty) - #expect(try inventory(fixture.root) == before) - #expect(try fixture.success(["manifest", "dump", "--json"] + arguments).stdout == dump) - } - - @Test(arguments: ["project", "user"]) - func warningsAreSuccessfulAndLocated(_ scope: String) throws { - let fixture = try CLIFixture() - try fixture.writeManifest( - "version: 1\nsources:\n rules: {url: github.com/example/rules}\n", scope: scope) - let before = try inventory(fixture.root) - let result = try fixture.run(["manifest", "check", "--scope", scope]) - #expect(result.status == 0 && result.stdout.isEmpty) - #expect( - result.stderr.contains( - "\(fixture.state("agents.yaml", scope: scope).path):3: warning [manifest.domain]:")) - #expect(result.stderr.contains("(UTF-8 byte column ")) - #expect(!result.stderr.contains("Error:") && !result.stderr.contains("Fix the reported")) - #expect(try inventory(fixture.root) == before) - } - - @Test(arguments: ["project", "user"]) - func errorsUseLineCoordinatesWithByteColumnsInMessages(_ scope: String) throws { - let fixture = try CLIFixture() - let prefix = "sources: {'🙂e\u{301}': {path: .}, " - try fixture.writeManifest( - "\u{FEFF}version: 1\r\n# Saved document\r\n" + prefix - + #"same: {path: .}, "\u0073ame": {path: .}}"#, scope: scope) - let before = try inventory(fixture.root) - let result = try fixture.run(["manifest", "check", "--scope", scope]) - #expect(result.status == 1 && result.stdout.isEmpty) - #expect( - result.stderr.hasPrefix( - "\(fixture.state("agents.yaml", scope: scope).path):3: error [manifest.key.duplicate]:")) - #expect(result.stderr.hasSuffix("(UTF-8 byte column \(prefix.utf8.count + 1))\n")) - #expect(!result.stderr.contains("related location") && !result.stderr.contains("Error:")) - #expect(try inventory(fixture.root) == before) - } - - @Test(arguments: ["project", "user"]) - func missingPendingAndIOFailuresAreCommandFailures(_ scope: String) throws { - let fixture = try CLIFixture() - let arguments = ["manifest", "check", "--scope", scope] - let missing = try fixture.run(arguments) - #expect(missing.status == 1 && missing.stdout.isEmpty) - #expect( - missing.stderr.contains("Not found: declaration at") - && missing.stderr.contains("Create agents.yaml")) - #expect(!missing.stderr.contains("[manifest.")) - #expect(!FileManager.default.fileExists(atPath: fixture.state("", scope: scope).path)) - try fixture.writeManifest("invalid YAML", scope: scope) - try Data("pending".utf8).write(to: fixture.state("transaction.new", scope: scope)) - let before = try inventory(fixture.root) - let pending = try fixture.run(arguments) - #expect(pending.status == 1 && pending.stdout.isEmpty) - #expect( - pending.stderr.contains("Transaction recovery is pending") - && !pending.stderr.contains("[manifest.")) - #expect(try inventory(fixture.root) == before) - try FileManager.default.removeItem(at: fixture.state("transaction.new", scope: scope)) - try FileManager.default.removeItem(at: fixture.state("agents.yaml", scope: scope)) - try FileManager.default.createDirectory( - at: fixture.state("agents.yaml", scope: scope), withIntermediateDirectories: true) - let ioBefore = try inventory(fixture.root) - let io = try fixture.run(arguments) - #expect(io.status == 1 && io.stdout.isEmpty && !io.stderr.contains("[manifest.")) - #expect(try inventory(fixture.root) == ioBefore) - } - - @Test(arguments: ["rules:12 [中文]🙂", "rules\nline", "rules\tname"]) - func specialPathsAndMessagesRemainSingleLine(_ name: String) throws { - let fixture = try CLIFixture() - let project = fixture.project.appendingPathComponent(name) - let state = project.appendingPathComponent(".agent") - try FileManager.default.createDirectory(at: state, withIntermediateDirectories: true) - try Data("version: 1\n\"unknown\\nfield\\u2028\": []\n".utf8).write( - to: state.appendingPathComponent("agents.yaml")) - let before = try inventory(fixture.root) - let result = try fixture.run(["manifest", "check"], directory: project) - #expect(result.status == 1 && result.stdout.isEmpty) - #expect(result.stderr.filter { $0 == "\n" }.count == 1) - #expect(result.stderr.contains("unknown\\nfield\\u{2028}")) - if name.contains("\n") || name.contains("\t") { - #expect(result.stderr.hasPrefix("Diagnostic at ")) - } else { - #expect( - result.stderr.hasPrefix( - state.appendingPathComponent("agents.yaml").path + ":2: error [manifest.schema]:")) - } - #expect(try inventory(fixture.root) == before) - } - - @Test(arguments: [ - ["manifest", "schema", "--json"], ["manifest", "schema", "--scope", "project"], - ["manifest", "schema", "file"], ["manifest", "check", "--json"], - ["manifest", "check", "--scope", "global"], ["manifest", "check", "file"], - ]) - func usageFailures(_ arguments: [String]) throws { - let fixture = try CLIFixture() - let before = try inventory(fixture.root) - let result = try fixture.run(arguments) - #expect(result.status == 64 && result.stdout.isEmpty) - #expect(result.stderr.contains("Run 'agents --help' for usage.")) - #expect(try inventory(fixture.root) == before) - } - - @Test func diagnosticLinesSanitizeMessagesAndAvoidFalsePathLinks() { - let diagnostic = ManifestDiagnostic( - code: "manifest.domain", message: "bad\r\nvalue\t\u{2028}\u{2029}\u{1B}", - span: SourceSpan( - document: DocumentIdentity("/project:a [b]/agents.yaml"), start: 0, end: 1, line: 3, - column: 9), - related: [ - SourceSpan( - document: DocumentIdentity("/other/agents.yaml"), start: 0, end: 1, line: 5, column: 7) - ]) - #expect( - ManifestDiagnostics.render(diagnostic) - == "/project:a [b]/agents.yaml:3: error [manifest.domain]: bad\\r\\nvalue\\t\\u{2028}\\u{2029}\\x1b (UTF-8 byte column 9)\n/other/agents.yaml:5: info [manifest.domain]: related location (UTF-8 byte column 7)\n" - ) - let unusual = ManifestDiagnostic( - code: "manifest.schema", message: "invalid", - span: SourceSpan( - document: DocumentIdentity("/project\nname/agents.yaml"), start: 0, end: 1, line: 2, - column: 1)) - #expect( - ManifestDiagnostics.render(unusual).hasPrefix( - "Diagnostic at /project\\nname/agents.yaml (line 2): error [manifest.schema]:")) - } - - private func inventory(_ root: URL) throws -> [String: String] { - let manager = FileManager.default - // CLIFixture owns these two root-level output captures; every CLI state path stays included. - return try Dictionary( - uniqueKeysWithValues: manager.subpathsOfDirectory(atPath: root.path).filter { - $0 != "stdout" && $0 != "stderr" - }.map { path in - let url = root.appendingPathComponent(path) - let values = try url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) - if values.isSymbolicLink == true { - return (path, "link:" + (try manager.destinationOfSymbolicLink(atPath: url.path))) - } - if values.isDirectory == true { return (path, "directory") } - return (path, "file:" + (try Data(contentsOf: url)).base64EncodedString()) - }) - } -} From 04a464c2132560fda53928f1ce5bb0099a6a734e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:21:35 +0800 Subject: [PATCH 10/67] build: align core configuration APIs --- Package.resolved | 66 ++++++++++++++++++++++++++++++++++++++++++++++-- Package.swift | 2 +- 2 files changed, 65 insertions(+), 3 deletions(-) diff --git a/Package.resolved b/Package.resolved index 548766b..7ebfa00 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,21 @@ { - "originHash" : "a4735c1303f29d22b9b25bcbbcde3d50094a71909a3bbb2ab53a59363a1da4a5", + "originHash" : "0e55681085649f266c89582101bf2af8fbc1729e9f5f06d332c7e7c45fdd14eb", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da" + "revision" : "c5e7f2d2dce85d42ddc2d14f93dc665005acf937" + } + }, + { + "identity" : "eventsource", + "kind" : "remoteSourceControl", + "location" : "https://github.com/mattt/eventsource.git", + "state" : { + "revision" : "bb4b61273b5a976bb571859c17f903ebc3439df1", + "version" : "1.6.0" } }, { @@ -27,6 +36,15 @@ "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", @@ -36,6 +54,15 @@ "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", @@ -45,6 +72,15 @@ "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", @@ -54,6 +90,32 @@ "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" + } + }, + { + "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", diff --git a/Package.swift b/Package.swift index 2ebcc4b..78a5d9c 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da"), + revision: "c5e7f2d2dce85d42ddc2d14f93dc665005acf937"), ], targets: [ .executableTarget( From db331be28c9e67f8a7c2faf6de6a0a26ea657248 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:21:59 +0800 Subject: [PATCH 11/67] feat: manage components and source imports --- Documentation/README.md | 5 +- Documentation/Reference/CLI.md | 131 +++++++-- Documentation/Reference/ManifestDump.md | 2 +- .../Schemas/components-list.schema.json | 94 +++++++ .../Reference/Schemas/components.schema.json | 135 +++++++++ .../Reference/Schemas/doctor.schema.json | 5 +- .../Reference/Schemas/import.schema.json | 166 ++++++++++++ .../Reference/Schemas/install.schema.json | 8 +- .../Reference/Schemas/mcp-test.schema.json | 70 +++++ .../Reference/Schemas/update.schema.json | 8 +- README.md | 36 ++- Sources/CLI/BindingOptions.swift | 59 ++++ Sources/CLI/ComponentCommands.swift | 209 ++++++++++++++ Sources/CLI/ComponentReports.swift | 143 ++++++++++ Sources/CLI/EntryPoint.swift | 12 +- Sources/CLI/ImportCommand.swift | 143 ++++++++++ Sources/CLI/InstructionReports.swift | 11 +- Sources/CLI/JSONReports.swift | 41 ++- Sources/CLI/LifecycleCommands.swift | 54 ++-- Sources/CLI/MCPCommand.swift | 83 ++++++ Sources/CLI/Terminal.swift | 1 + Tests/CLITests/ComponentExecutableTests.swift | 256 ++++++++++++++++++ Tests/CLITests/ExecutableTests.swift | 13 +- .../CLITests/InstructionExecutableTests.swift | 3 +- Tests/CLITests/ManifestExecutableTests.swift | 2 +- Tests/CLITests/UpdateReportingTests.swift | 2 +- 26 files changed, 1615 insertions(+), 77 deletions(-) create mode 100644 Documentation/Reference/Schemas/components-list.schema.json create mode 100644 Documentation/Reference/Schemas/components.schema.json create mode 100644 Documentation/Reference/Schemas/import.schema.json create mode 100644 Documentation/Reference/Schemas/mcp-test.schema.json create mode 100644 Sources/CLI/BindingOptions.swift create mode 100644 Sources/CLI/ComponentCommands.swift create mode 100644 Sources/CLI/ComponentReports.swift create mode 100644 Sources/CLI/ImportCommand.swift create mode 100644 Sources/CLI/MCPCommand.swift create mode 100644 Tests/CLITests/ComponentExecutableTests.swift diff --git a/Documentation/README.md b/Documentation/README.md index 60539e7..99be2d5 100644 --- a/Documentation/README.md +++ b/Documentation/README.md @@ -14,8 +14,9 @@ This directory indexes repository-native documentation for `agents-tools/cli`. state locations, and JSON contracts. - [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 list, - update previews, watch status and diffs, installation, and doctor. +- [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 19adfd7..b5436c2 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -1,8 +1,9 @@ # 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`. `AgentsManifest` +`AgentsInstructions`; combined lifecycle, component inspection, import and MCP +tests use `AgentsUpdates`. `AgentsManifest` owns declaration parsing and editing, and the manifest dump contract. ## Commands @@ -26,9 +27,14 @@ 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 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 mcp test [--kind mcpServer] [--identity ] [--occurrence ] [--binding NAME=ENV_VAR] [--json] [--scope project|user] agents manifest dump --json [--scope project|user] -agents install [--json] -agents update [--apply | --json] +agents install [--json] [--binding NAME=ENV_VAR] +agents update [--apply | --json] [--binding NAME=ENV_VAR] [--replace] [--changing-access] agents doctor [--root …] [--json] ``` @@ -40,7 +46,7 @@ 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 @@ -262,6 +268,85 @@ code on stderr; related locations follow when available. Invalid arguments exit 64. See the [dump contract](ManifestDump.md) for encoding and schema ownership. +## Components + +`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. + +## 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 @@ -480,9 +565,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 @@ -519,7 +604,7 @@ 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 @@ -532,12 +617,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. @@ -545,14 +630,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. `--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 @@ -564,7 +651,7 @@ current directory and user scope uses HOME. | 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/953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/c5e7f2d2dce85d42ddc2d14f93dc665005acf937/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 @@ -699,15 +786,18 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | `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` | +| `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 test --json` | [MCP test](Schemas/mcp-test.schema.json) | `schemaVersion`, `kind`, `transport`, `outcome`, `cleanupComplete`, `elapsed`, `tools` | An empty installed list: @@ -737,7 +827,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. @@ -762,6 +852,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` diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 2767d6e..74348b0 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/c5e7f2d2dce85d42ddc2d14f93dc665005acf937/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. 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 050dc68..da526af 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": { @@ -51,7 +51,8 @@ "kind": { "enum": [ "skills", - "instructions" + "instructions", + "components" ] } }, 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..989b035 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,12 @@ }, "instructions": { "$ref": "instructions.schema.json#/$defs/changes" + }, + "components": { + "type": "array", + "items": { + "$ref": "components.schema.json#/$defs/change" + } } }, "required": [ 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..075ceb9 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,12 @@ "lockMissing": { "type": "boolean", "description": "Combined preview: no resolved state existed when preparation began." + }, + "components": { + "type": "array", + "items": { + "$ref": "components.schema.json#/$defs/change" + } } }, "required": [ diff --git a/README.md b/README.md index 66688cd..705887a 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@

agents

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

@@ -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, and OpenCode through [agents-tools/core](https://github.com/agents-tools/core). The executable owns commands and terminal presentation. Core owns source @@ -108,10 +108,17 @@ 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/953bf63f6f0fa9bd468bc72fab1c6cbe1d0fb1da/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/c5e7f2d2dce85d42ddc2d14f93dc665005acf937/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. @@ -135,9 +142,22 @@ remove, or update sets the recipients of the scope's entire section list. 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 diff --git a/Sources/CLI/BindingOptions.swift b/Sources/CLI/BindingOptions.swift new file mode 100644 index 0000000..02eaf11 --- /dev/null +++ b/Sources/CLI/BindingOptions.swift @@ -0,0 +1,59 @@ +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 { + 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 --binding NAME=ENV_VAR mappings") } + variables[String(parts[0])] = String(parts[1]) + } + return EnvironmentBindings(variables: 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/ComponentCommands.swift b/Sources/CLI/ComponentCommands.swift new file mode 100644 index 0000000..acd082d --- /dev/null +++ b/Sources/CLI/ComponentCommands.swift @@ -0,0 +1,209 @@ +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, AddComponents.self, RemoveComponents.self]) +} + +/// 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: ParsableCommand { + 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() throws { + let result = try withRecovery { + let inspection = try UpdateOperations.inspect(scope: location.scope) + let selected = try selection.select(in: inspection) + let request = UpdateRequest( + operation: .remove, selections: [selected], agents: agents.recipients) + return try UpdateOperations.withPreparedUpdate( + writing.request(request), 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) + } +} 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 781eb0c..77e425a 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -14,7 +14,7 @@ enum BuildInfo { 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 @@ -27,7 +27,7 @@ struct Agents: ParsableCommand { """, subcommands: [ Skills.self, InstructionsCommand.self, Watch.self, Manifest.self, Install.self, Update.self, - Doctor.self, + Doctor.self, ComponentsCommand.self, ImportCommand.self, MCPCommand.self, ] ) @@ -49,7 +49,7 @@ struct Skills: ParsableCommand { @main enum EntryPoint { - static func main() { + static func main() async { var command: any ParsableCommand do { let arguments = Array(CommandLine.arguments.dropFirst()) @@ -70,7 +70,11 @@ enum EntryPoint { 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 { 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/InstructionReports.swift b/Sources/CLI/InstructionReports.swift index fd03067..e73f5dc 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 @@ -246,11 +247,13 @@ struct InstallReport: Encodable { let scope: String let skills: [RestoredSkill] let instructions: InstructionChanges + let components: [ComponentChangeItem] - init(scope: String, skills: [InstallResult], instructions: InstructionChanges) { - self.scope = scope - self.skills = skills.map(RestoredSkill.init) - self.instructions = instructions + init(_ result: UpdateApplyResult) { + 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 18fa434..193b717 100644 --- a/Sources/CLI/JSONReports.swift +++ b/Sources/CLI/JSONReports.swift @@ -75,6 +75,7 @@ struct UpdateReport: Encodable { let instructions: InstructionChanges? let lockMissing: Bool? + let components: [ComponentChangeItem]? init(scope: String, results: [UpdateResult]) { self.scope = scope @@ -82,6 +83,7 @@ struct UpdateReport: Encodable { skills = results.map(UpdateItem.init) instructions = nil lockMissing = nil + components = nil } init(_ report: CombinedUpdateReport) { @@ -90,6 +92,7 @@ struct UpdateReport: Encodable { skills = report.skills.map(UpdateItem.init) instructions = InstructionChanges(report.instructions) lockMissing = report.lockMissing + components = report.components.map(ComponentChangeItem.init) } } @@ -230,13 +233,14 @@ struct DoctorRoot: Encodable { init( root: String, scope: String, report: DoctorReport, instructions: InstructionDoctorReport, - environment: RuntimeEnvironment + environment: RuntimeEnvironment, inventory: ScopeInspection? = nil ) { self.root = root self.scope = scope checks = report.checks.map { CheckItem($0, environment: environment) } + instructions.diagnostics.map { CheckItem($0, environment: environment) } + + (inventory.map { CheckItem.inventory($0, environment: environment) } ?? []) ok = !checks.contains { $0.status == "error" } } } @@ -277,6 +281,41 @@ struct CheckItem: Encodable { path = diagnostic.path?.path } + 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)) + return 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 442f7ff..5f28746 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -8,38 +8,32 @@ import Foundation struct Install: ParsableCommand { 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) + let result = try withRecovery { + try UpdateOperations.restore(scope: location.scope, bindingProvider: bindings.provider()) } - if !json { - if report.installed.isEmpty { + if json { + try Terminal.json(InstallReport(result)) + } else { + 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 { + Terminal.write("Restored instructions in \(location.paths.path(target.url.path)).\n") + } } + Terminal.componentChanges(result.report.components, paths: location.paths, applied: true) } } } @@ -104,23 +98,28 @@ struct UpdateOptions: ParsableArguments { struct Update: ParsableCommand { 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 { let paths = options.location.paths if options.apply { let receipt = try withRecovery { - try UpdateOperations.withPreparedUpdate(scope: options.location.scope) { update in + try UpdateOperations.withPreparedUpdate( + writing.request(), scope: options.location.scope, + bindingProvider: writing.bindings.provider() + ) { update in Terminal.updateDifferences(update.report, paths: paths) return try update.apply() } } 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) } 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 { @@ -152,7 +151,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." ) @@ -191,11 +190,12 @@ 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) 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)) } let report = DoctorOutput(roots: reports) if json { diff --git a/Sources/CLI/MCPCommand.swift b/Sources/CLI/MCPCommand.swift new file mode 100644 index 0000000..cf1c4fc --- /dev/null +++ b/Sources/CLI/MCPCommand.swift @@ -0,0 +1,83 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct MCPCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "mcp", + abstract: "Explicitly test a managed MCP connection.", subcommands: [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/Terminal.swift b/Sources/CLI/Terminal.swift index 95ad8be..6d548e9 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -344,6 +344,7 @@ enum Terminal { write("No changes.\n") return } + componentChanges(report.components, paths: paths, applied: false) let skills = report.skills let instructions = report.instructions missingSkillLock(report.lockMissing && !skills.isEmpty) diff --git a/Tests/CLITests/ComponentExecutableTests.swift b/Tests/CLITests/ComponentExecutableTests.swift new file mode 100644 index 0000000..752ef27 --- /dev/null +++ b/Tests/CLITests/ComponentExecutableTests.swift @@ -0,0 +1,256 @@ +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 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 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"], ["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 721f5ca..bb34f90 100644 --- a/Tests/CLITests/ExecutableTests.swift +++ b/Tests/CLITests/ExecutableTests.swift @@ -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]]) @@ -227,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") @@ -399,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( """ diff --git a/Tests/CLITests/InstructionExecutableTests.swift b/Tests/CLITests/InstructionExecutableTests.swift index 3c6fec1..6b32b4a 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -449,7 +449,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) diff --git a/Tests/CLITests/ManifestExecutableTests.swift b/Tests/CLITests/ManifestExecutableTests.swift index e8c8fc0..6bd4980 100644 --- a/Tests/CLITests/ManifestExecutableTests.swift +++ b/Tests/CLITests/ManifestExecutableTests.swift @@ -287,7 +287,7 @@ struct ManifestExecutableTests { let checks = try #require(roots.first?["checks"] as? [[String: Any]]) #expect( checks.compactMap { $0["id"] as? String } == [ - "unresolved-transaction", "unresolvedTransaction", + "unresolved-transaction", "unresolvedTransaction", "unresolved-transaction", ]) #expect(checks.allSatisfy { $0["status"] as? String == "error" }) #expect( diff --git a/Tests/CLITests/UpdateReportingTests.swift b/Tests/CLITests/UpdateReportingTests.swift index 33c0ad0..3d6dac6 100644 --- a/Tests/CLITests/UpdateReportingTests.swift +++ b/Tests/CLITests/UpdateReportingTests.swift @@ -139,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)) } From ee59ac7bfb5479c81e2e6391b76be5ff00f401ac Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:15:41 +0800 Subject: [PATCH 12/67] test: align locked restore and scoped update expectations --- Documentation/Reference/CLI.md | 7 ++-- Tests/CLITests/HumanExecutableTests.swift | 33 +++++++++++++++---- .../CLITests/InstructionExecutableTests.swift | 27 ++++++++++----- 3 files changed, 50 insertions(+), 17 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index b5436c2..9b7dfcb 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -606,9 +606,10 @@ for an edited target it keeps. `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` diff --git a/Tests/CLITests/HumanExecutableTests.swift b/Tests/CLITests/HumanExecutableTests.swift index a125e16..4a9029f 100644 --- a/Tests/CLITests/HumanExecutableTests.swift +++ b/Tests/CLITests/HumanExecutableTests.swift @@ -26,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 .")) @@ -206,8 +213,22 @@ struct HumanExecutableTests { #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 { diff --git a/Tests/CLITests/InstructionExecutableTests.swift b/Tests/CLITests/InstructionExecutableTests.swift index 6b32b4a..175fc9e 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -280,15 +280,26 @@ struct InstructionExecutableTests { == generated(["# guide\n\nWrite the instructions here."])) let declaration = try fixture.declaration() #expect(try declaration.instructions?.sections == ["guide"]) - try Data( - "---\ndescription: Guide.\n---\n# guide\n\nEdited instructions.\n".utf8 - ).write(to: own) - let install = try fixture.run(["install"]) + 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") From d0e656149df02603869e9592763691a6f135f0e8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:17:30 +0800 Subject: [PATCH 13/67] build: integrate configuration lifecycle fixes --- Package.resolved | 4 ++-- Package.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Package.resolved b/Package.resolved index 7ebfa00..ce69afe 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "0e55681085649f266c89582101bf2af8fbc1729e9f5f06d332c7e7c45fdd14eb", + "originHash" : "7616c24270df307d3945a20e9e501c6dbe8fdf0a802e3e7a19360e847fc64072", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "c5e7f2d2dce85d42ddc2d14f93dc665005acf937" + "revision" : "25e63b99bfa4bded208a96f1a1465db3023e589b" } }, { diff --git a/Package.swift b/Package.swift index 78a5d9c..e13cf80 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "c5e7f2d2dce85d42ddc2d14f93dc665005acf937"), + revision: "25e63b99bfa4bded208a96f1a1465db3023e589b"), ], targets: [ .executableTarget( From 1f701503906e985de748d9ff266b642295d60812 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 16:46:13 +0800 Subject: [PATCH 14/67] fix(cli): read skill completion membership from resolved state --- Sources/CLI/SkillRendering.swift | 17 +---------- .../CLITests/SkillOutputExecutableTests.swift | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+), 16 deletions(-) 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/Tests/CLITests/SkillOutputExecutableTests.swift b/Tests/CLITests/SkillOutputExecutableTests.swift index 92506fa..b805494 100644 --- a/Tests/CLITests/SkillOutputExecutableTests.swift +++ b/Tests/CLITests/SkillOutputExecutableTests.swift @@ -127,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() @@ -138,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"]) From 88cdffea80741834e0c99532e827ae11a3429558 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 17 Nov 2026 21:01:32 +0800 Subject: [PATCH 15/67] build: align complete configuration management --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 9b7dfcb..97ff771 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -652,7 +652,7 @@ current directory and user scope uses HOME. | 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/c5e7f2d2dce85d42ddc2d14f93dc665005acf937/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/25187e040ca0dd98e96c48704a4a7e95d4da198c/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 74348b0..5220d1f 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/c5e7f2d2dce85d42ddc2d14f93dc665005acf937/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/25187e040ca0dd98e96c48704a4a7e95d4da198c/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. diff --git a/Package.resolved b/Package.resolved index ce69afe..59909b6 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "7616c24270df307d3945a20e9e501c6dbe8fdf0a802e3e7a19360e847fc64072", + "originHash" : "e32c6db9171af8e01c5fa15423ccdc7b9d1a06f926783fe145c4e1c3b1395838", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "25e63b99bfa4bded208a96f1a1465db3023e589b" + "revision" : "25187e040ca0dd98e96c48704a4a7e95d4da198c" } }, { diff --git a/Package.swift b/Package.swift index e13cf80..cc9a8f1 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "25e63b99bfa4bded208a96f1a1465db3023e589b"), + revision: "25187e040ca0dd98e96c48704a4a7e95d4da198c"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 705887a..c9534a8 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/c5e7f2d2dce85d42ddc2d14f93dc665005acf937/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/25187e040ca0dd98e96c48704a4a7e95d4da198c/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From d1922ad4c8c04f238c4a48ca9cad0a5409811f39 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:20:52 +0800 Subject: [PATCH 16/67] chore: prepare 0.3.0 configuration support --- CHANGELOG.md | 16 ++++++++++++++++ Sources/CLI/EntryPoint.swift | 2 +- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3401fdb..ed8c3c1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,22 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## [0.3.0] + +### 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). + +### Changed + +- Project declarations use `.agent/agents.yaml` and user declarations use + `~/.agents/agents.yaml`. Prepare the YAML declaration for an existing scope + before applying changes. 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/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index 77e425a..b53f32a 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -8,7 +8,7 @@ import Foundation #endif enum BuildInfo { - static let version = "0.2.0" + static let version = "0.3.0" } struct Agents: ParsableCommand { From a67d94abb2079b13a3d73fa67e85a0b63f16fc87 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:23:13 +0800 Subject: [PATCH 17/67] build: align final configuration integration --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 97ff771..f2bf8e0 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -652,7 +652,7 @@ current directory and user scope uses HOME. | 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/25187e040ca0dd98e96c48704a4a7e95d4da198c/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/b01aaa18352e560566d7244a864e5c543e39f322/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 5220d1f..a24d056 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/25187e040ca0dd98e96c48704a4a7e95d4da198c/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/b01aaa18352e560566d7244a864e5c543e39f322/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. diff --git a/Package.resolved b/Package.resolved index 59909b6..7f2abbe 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "e32c6db9171af8e01c5fa15423ccdc7b9d1a06f926783fe145c4e1c3b1395838", + "originHash" : "ba5f7e2763b5ad164c12119e862d919d6e6b92af4a0e5abaa9b1cc88038ce256", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "25187e040ca0dd98e96c48704a4a7e95d4da198c" + "revision" : "b01aaa18352e560566d7244a864e5c543e39f322" } }, { diff --git a/Package.swift b/Package.swift index cc9a8f1..a75dee2 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "25187e040ca0dd98e96c48704a4a7e95d4da198c"), + revision: "b01aaa18352e560566d7244a864e5c543e39f322"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index c9534a8..ca3c184 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/25187e040ca0dd98e96c48704a4a7e95d4da198c/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/b01aaa18352e560566d7244a864e5c543e39f322/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From c60973b60048017a6cfde5b80654edf51f3de37f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:04:04 +0800 Subject: [PATCH 18/67] build: align final configuration integration --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index f2bf8e0..d0302bc 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -652,7 +652,7 @@ current directory and user scope uses HOME. | 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/b01aaa18352e560566d7244a864e5c543e39f322/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/46c3bf9e158b9501e6267864d4ce57dc21c3058b/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index a24d056..9b5ddfe 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/b01aaa18352e560566d7244a864e5c543e39f322/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/46c3bf9e158b9501e6267864d4ce57dc21c3058b/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. diff --git a/Package.resolved b/Package.resolved index 7f2abbe..5068776 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "ba5f7e2763b5ad164c12119e862d919d6e6b92af4a0e5abaa9b1cc88038ce256", + "originHash" : "2b0164720a46a06c1a7c02e8b72a3c6a5d3b6fc6ecfca658101c46720dd7a78f", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "b01aaa18352e560566d7244a864e5c543e39f322" + "revision" : "46c3bf9e158b9501e6267864d4ce57dc21c3058b" } }, { diff --git a/Package.swift b/Package.swift index a75dee2..a0ba0a2 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "b01aaa18352e560566d7244a864e5c543e39f322"), + revision: "46c3bf9e158b9501e6267864d4ce57dc21c3058b"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index ca3c184..c48ffdc 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/b01aaa18352e560566d7244a864e5c543e39f322/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/46c3bf9e158b9501e6267864d4ce57dc21c3058b/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 0cef796060a18af3d0e22b0b0dfca02a212525e7 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:35:41 +0800 Subject: [PATCH 19/67] build: align final configuration integration --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index d0302bc..dec85db 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -652,7 +652,7 @@ current directory and user scope uses HOME. | 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/46c3bf9e158b9501e6267864d4ce57dc21c3058b/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/22e88e969edb1733c7487e845b8755ad26407b3a/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 9b5ddfe..1090820 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/46c3bf9e158b9501e6267864d4ce57dc21c3058b/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/22e88e969edb1733c7487e845b8755ad26407b3a/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. diff --git a/Package.resolved b/Package.resolved index 5068776..ebe3006 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "2b0164720a46a06c1a7c02e8b72a3c6a5d3b6fc6ecfca658101c46720dd7a78f", + "originHash" : "a260c89cd8c51fdb5f1fca47548d54668601f3a5b75e87a7aece96a97b992ff1", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "46c3bf9e158b9501e6267864d4ce57dc21c3058b" + "revision" : "22e88e969edb1733c7487e845b8755ad26407b3a" } }, { diff --git a/Package.swift b/Package.swift index a0ba0a2..3d80ae9 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "46c3bf9e158b9501e6267864d4ce57dc21c3058b"), + revision: "22e88e969edb1733c7487e845b8755ad26407b3a"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index c48ffdc..69e77f4 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/46c3bf9e158b9501e6267864d4ce57dc21c3058b/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/22e88e969edb1733c7487e845b8755ad26407b3a/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 554856abd61d821e4be56dcd9cd4961b01da218c Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:58:41 +0800 Subject: [PATCH 20/67] build: align final configuration integration --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index dec85db..e4ee2ba 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -652,7 +652,7 @@ current directory and user scope uses HOME. | 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/22e88e969edb1733c7487e845b8755ad26407b3a/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/0ce4ff8670a0447f452869a5170b46ddd8133795/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 1090820..6d880c4 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/22e88e969edb1733c7487e845b8755ad26407b3a/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/0ce4ff8670a0447f452869a5170b46ddd8133795/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. diff --git a/Package.resolved b/Package.resolved index ebe3006..6a2b7f6 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "a260c89cd8c51fdb5f1fca47548d54668601f3a5b75e87a7aece96a97b992ff1", + "originHash" : "74e03da5c15cd80845834c82598ed3770dffc45b4411d8145ea17183b667461e", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "22e88e969edb1733c7487e845b8755ad26407b3a" + "revision" : "0ce4ff8670a0447f452869a5170b46ddd8133795" } }, { diff --git a/Package.swift b/Package.swift index 3d80ae9..2957b74 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "22e88e969edb1733c7487e845b8755ad26407b3a"), + revision: "0ce4ff8670a0447f452869a5170b46ddd8133795"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 69e77f4..cbd610d 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/22e88e969edb1733c7487e845b8755ad26407b3a/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/0ce4ff8670a0447f452869a5170b46ddd8133795/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From d74c3725f61e44cb82215098030ceb0fbd6d5843 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 04:25:09 +0800 Subject: [PATCH 21/67] fix: prepare file capacity before reading configuration --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- Sources/CLI/EntryPoint.swift | 2 ++ 6 files changed, 8 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index e4ee2ba..663f34d 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -652,7 +652,7 @@ current directory and user scope uses HOME. | 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/0ce4ff8670a0447f452869a5170b46ddd8133795/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/c15076ca3a0b0db2ccffa2df10e342e03f1754c5/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 6d880c4..6b59e7e 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/0ce4ff8670a0447f452869a5170b46ddd8133795/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/c15076ca3a0b0db2ccffa2df10e342e03f1754c5/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. diff --git a/Package.resolved b/Package.resolved index 6a2b7f6..4a75709 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "74e03da5c15cd80845834c82598ed3770dffc45b4411d8145ea17183b667461e", + "originHash" : "5a0b42d2f13fa2f78ca58426c772136ec9241ad17f33a8d86dd677fc3dc1c2f9", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "0ce4ff8670a0447f452869a5170b46ddd8133795" + "revision" : "c15076ca3a0b0db2ccffa2df10e342e03f1754c5" } }, { diff --git a/Package.swift b/Package.swift index 2957b74..0b78bb2 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "0ce4ff8670a0447f452869a5170b46ddd8133795"), + revision: "c15076ca3a0b0db2ccffa2df10e342e03f1754c5"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index cbd610d..5e9e95a 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/0ce4ff8670a0447f452869a5170b46ddd8133795/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/c15076ca3a0b0db2ccffa2df10e342e03f1754c5/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. diff --git a/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index b53f32a..d849a1f 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -1,3 +1,4 @@ +import AgentsCore import ArgumentParser import Foundation @@ -50,6 +51,7 @@ struct Skills: ParsableCommand { @main enum EntryPoint { static func main() async { + ProcessLimits.raiseOpenFileLimit() var command: any ParsableCommand do { let arguments = Array(CommandLine.arguments.dropFirst()) From ed627fb9ea307407097eaca7840451d9e8d91851 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:07:29 +0800 Subject: [PATCH 22/67] build: pin verified configuration core --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 663f34d..6812302 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -652,7 +652,7 @@ current directory and user scope uses HOME. | 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/c15076ca3a0b0db2ccffa2df10e342e03f1754c5/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/3979cb22b415cfe6c502a9421e2c4928a135a698/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 6b59e7e..4ee7a67 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/c15076ca3a0b0db2ccffa2df10e342e03f1754c5/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/3979cb22b415cfe6c502a9421e2c4928a135a698/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. diff --git a/Package.resolved b/Package.resolved index 4a75709..42ee8fd 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "5a0b42d2f13fa2f78ca58426c772136ec9241ad17f33a8d86dd677fc3dc1c2f9", + "originHash" : "7135b9bfde396792b8473387a9990bb0d174a6fbff2d2c8dcb68f629dee45112", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "c15076ca3a0b0db2ccffa2df10e342e03f1754c5" + "revision" : "3979cb22b415cfe6c502a9421e2c4928a135a698" } }, { diff --git a/Package.swift b/Package.swift index 0b78bb2..5c55895 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "c15076ca3a0b0db2ccffa2df10e342e03f1754c5"), + revision: "3979cb22b415cfe6c502a9421e2c4928a135a698"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 5e9e95a..0cf7dc6 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/c15076ca3a0b0db2ccffa2df10e342e03f1754c5/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/3979cb22b415cfe6c502a9421e2c4928a135a698/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 2b30d2926bfee349b70b825f895bc0fd01d98091 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:15:22 +0800 Subject: [PATCH 23/67] ci: validate public agent declarations with shared policy --- .github/workflows/source-policy.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/source-policy.yml b/.github/workflows/source-policy.yml index b6a1735..dc3b0cd 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@c2d32f7279064a45dd7cc152bd4be471ddc8ce33 with: allow-terms: | ChatGPT From e7697921dc7410cd01067c1ddec0a51e11101a21 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:25:17 +0800 Subject: [PATCH 24/67] build: pin verified configuration core --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 6812302..45050d9 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -652,7 +652,7 @@ current directory and user scope uses HOME. | 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/3979cb22b415cfe6c502a9421e2c4928a135a698/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/048cbf3f23c8a9986ca3de8654f7ec5f758161ae/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 4ee7a67..3ad02f9 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/3979cb22b415cfe6c502a9421e2c4928a135a698/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/048cbf3f23c8a9986ca3de8654f7ec5f758161ae/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. diff --git a/Package.resolved b/Package.resolved index 42ee8fd..4e424e5 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "7135b9bfde396792b8473387a9990bb0d174a6fbff2d2c8dcb68f629dee45112", + "originHash" : "9b24deb76b28f51da39063d7483656a517ce01a8ee5943ec4958ac91b80ea8b5", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "3979cb22b415cfe6c502a9421e2c4928a135a698" + "revision" : "048cbf3f23c8a9986ca3de8654f7ec5f758161ae" } }, { diff --git a/Package.swift b/Package.swift index 5c55895..dcd248c 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "3979cb22b415cfe6c502a9421e2c4928a135a698"), + revision: "048cbf3f23c8a9986ca3de8654f7ec5f758161ae"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 0cf7dc6..b1e28c8 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/3979cb22b415cfe6c502a9421e2c4928a135a698/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/048cbf3f23c8a9986ca3de8654f7ec5f758161ae/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 8fb10a71da01f10976a79af7dd79555e329d09af Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:29:57 +0800 Subject: [PATCH 25/67] ci: align shared workflow revisions --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7907540..7973717 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@c2d32f7279064a45dd7cc152bd4be471ddc8ce33 From 5c18ebd42bc2a02a30778ea9debdbd03a762eee6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:45:16 +0800 Subject: [PATCH 26/67] feat: expose Antigravity instruction rules in the CLI --- Documentation/Reference/CLI.md | 58 +++++--- .../Schemas/instructions.schema.json | 12 ++ README.md | 5 +- Sources/CLI/InstructionCommands.swift | 61 +++++---- Sources/CLI/InstructionReports.swift | 4 + Sources/CLI/LifecycleCommands.swift | 13 +- Sources/CLI/Options.swift | 12 +- Sources/CLI/Terminal.swift | 42 ++++-- Tests/CLITests/HumanExecutableTests.swift | 2 +- .../CLITests/InstructionExecutableTests.swift | 126 +++++++++++++++++- Tests/CLITests/ParsingTests.swift | 2 + 11 files changed, 266 insertions(+), 71 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 45050d9..2eb1b68 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -67,7 +67,7 @@ Examples: | `--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` | +| `--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` | @@ -75,9 +75,9 @@ Examples: | `--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`; `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 agents are `codex`, `claude-code`, `cursor`, `gemini-cli`, and `opencode`. +Instructions also accept `antigravity` in user scope. 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 @@ -182,25 +182,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 is a user-scope instruction recipient. Its app and `agy` read one +managed Markdown file per selected section under `~/.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 @@ -581,9 +596,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. @@ -594,7 +609,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. ``` @@ -840,10 +855,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 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/README.md b/README.md index b1e28c8..32226c1 100644 --- a/README.md +++ b/README.md @@ -134,8 +134,9 @@ 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 `--scope user --agent antigravity` +on `instructions add` to install the selected sections as individual Markdown +rules in `~/.gemini/config/rules/`. `agents instructions init ` creates `.agent/instructions/.md`, and `agents instructions export` maps locked targets to their sections. diff --git a/Sources/CLI/InstructionCommands.swift b/Sources/CLI/InstructionCommands.swift index 6f70a2e..d54b9e7 100644 --- a/Sources/CLI/InstructionCommands.swift +++ b/Sources/CLI/InstructionCommands.swift @@ -19,7 +19,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. Antigravity requires --scope user. Omit to use the configured default recipients.", transform: AgentID.parse) var agent: [AgentID] = [] @@ -30,7 +30,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 --scope user, add the selected sections as global Antigravity rules. Other sections keep their recipients." + ) @Argument( help: @@ -56,29 +59,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" ) } } @@ -129,7 +133,8 @@ struct ListInstructions: ParsableCommand { struct RemoveInstructions: ParsableCommand { 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] @@ -144,20 +149,20 @@ struct RemoveInstructions: ParsableCommand { let result = try withRecovery { try InstructionOperations.remove( names: names, scope: location.scope, agents: agents.recipients, - beforeApply: { Terminal.instructionTargets($0.targets, paths: location.paths) }) - } - 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" - ) + beforeApply: { + Terminal.instructionNotes($0) + Terminal.instructionTargets($0, paths: location.paths) + }) } + Terminal.updatedInstructions(result, paths: location.paths) Terminal.promptReminder(result.changedPrompts) } } struct UpdateInstructions: ParsableCommand { 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 diff --git a/Sources/CLI/InstructionReports.swift b/Sources/CLI/InstructionReports.swift index e73f5dc..bcc74b2 100644 --- a/Sources/CLI/InstructionReports.swift +++ b/Sources/CLI/InstructionReports.swift @@ -118,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 } } diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index 5f28746..24d7b52 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -21,6 +21,7 @@ struct Install: ParsableCommand { if json { try Terminal.json(InstallReport(result)) } else { + Terminal.instructionNotes(result.report.instructions) if result.installedSkills.isEmpty { Terminal.write("No locked skills to restore.\n") } else { @@ -29,8 +30,12 @@ struct Install: ParsableCommand { if result.report.instructions.targets.isEmpty { Terminal.write("No locked instruction targets to restore.\n") } else { - for target in result.report.instructions.targets { - Terminal.write("Restored instructions in \(location.paths.path(target.url.path)).\n") + 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) @@ -84,7 +89,7 @@ struct UpdateOptions: ParsableArguments { Terminal.updatedInstructions(result, paths: location.paths) } else { Terminal.instructionDifferences(result, paths: location.paths) - previewNotice(changed: result.hasChanges) + previewNotice(changed: result.hasChanges && result.conflicts.isEmpty) } } @@ -124,7 +129,7 @@ struct Update: ParsableCommand { 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) } } } diff --git a/Sources/CLI/Options.swift b/Sources/CLI/Options.swift index b6fc2fa..6765368 100644 --- a/Sources/CLI/Options.swift +++ b/Sources/CLI/Options.swift @@ -23,7 +23,7 @@ struct AgentOptions: ParsableArguments { name: .long, help: "Limit to this agent: codex, claude-code, cursor, gemini-cli or opencode. Repeat for several. Default: all recipients.", - transform: AgentID.parse) + transform: parseSkillAgent) var agent: [AgentID] = [] var recipients: [AgentID]? { @@ -36,7 +36,7 @@ struct AddAgentOptions: ParsableArguments { 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) + 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 diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 6d548e9..06f91a5 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -145,6 +145,8 @@ 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 chatgpt in the instructions component of agents.yaml and run 'agents instructions update --apply'" @@ -340,13 +342,14 @@ 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 } 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 { @@ -362,23 +365,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" @@ -404,7 +417,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/Tests/CLITests/HumanExecutableTests.swift b/Tests/CLITests/HumanExecutableTests.swift index 4a9029f..5c242ad 100644 --- a/Tests/CLITests/HumanExecutableTests.swift +++ b/Tests/CLITests/HumanExecutableTests.swift @@ -84,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 { diff --git a/Tests/CLITests/InstructionExecutableTests.swift b/Tests/CLITests/InstructionExecutableTests.swift index 175fc9e..e8ef7ab 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -7,6 +7,124 @@ 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)) + + 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["path"] as? String == review.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 { + $0["path"] as? String == review.path + && $0["afterAgents"] as? [String] == ["antigravity"] && $0["changed"] as? Bool == true + }) + #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() @@ -564,12 +682,10 @@ 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("Antigravity requires --scope user.")) + #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 diff --git a/Tests/CLITests/ParsingTests.swift b/Tests/CLITests/ParsingTests.swift index f93a9d0..d40b430 100644 --- a/Tests/CLITests/ParsingTests.swift +++ b/Tests/CLITests/ParsingTests.swift @@ -116,6 +116,8 @@ struct ParsingTests { ["skills", "add", ".", "--from", "2.0.0", "--to", "1.0.0"], ["skills", "add", ".", "--mode", "edit", "--branch", "main"], ["skills", "list", "--scope", "global"], ["skills", "list", "--agent", "unknown"], + ["skills", "add", ".", "--agent", "antigravity"], + ["skills", "list", "--agent", "antigravity"], ["doctor", "--agent", "antigravity"], ["skills", "list", "--path", "skills"], ["skills", "list", "--full-depth"], ["install", "--agent", "codex"], ["install", "--mode", "copy"], ["install", "source"], ["update", "name"], ["update", "--apply", "--json"], From e75630c82c6eb8b16c60ec3216bbd9f16cbb8a92 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:15:23 +0800 Subject: [PATCH 27/67] test: resolve filesystem aliases in Antigravity report checks --- Tests/CLITests/InstructionExecutableTests.swift | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Tests/CLITests/InstructionExecutableTests.swift b/Tests/CLITests/InstructionExecutableTests.swift index e8ef7ab..be9555a 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -65,6 +65,15 @@ struct InstructionExecutableTests { #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) @@ -72,7 +81,7 @@ struct InstructionExecutableTests { #expect( checks.contains { $0["kind"] as? String == "instructions" - && $0["path"] as? String == review.path + && $0["id"] as? String == "missingTarget" && isReviewPath($0["path"]) }) let install = try fixture.success(["install", "--json"] + scope).json() @@ -80,8 +89,10 @@ struct InstructionExecutableTests { let targets = try #require(instructions["targets"] as? [[String: Any]]) #expect( targets.contains { - $0["path"] as? String == review.path + 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) From bae513fb96669acfc38f05e710118deae9bd62c4 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:59:06 +0800 Subject: [PATCH 28/67] build: pin verified configuration core --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 2eb1b68..774ffdb 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -667,7 +667,7 @@ current directory and user scope uses HOME. | 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/048cbf3f23c8a9986ca3de8654f7ec5f758161ae/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 3ad02f9..b10fc67 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/048cbf3f23c8a9986ca3de8654f7ec5f758161ae/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf/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. diff --git a/Package.resolved b/Package.resolved index 4e424e5..2cbef28 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "9b24deb76b28f51da39063d7483656a517ce01a8ee5943ec4958ac91b80ea8b5", + "originHash" : "e11990a3db11bc8b23269e077c217376ee1b0e435919dfea9c6b625dd2efdb33", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "048cbf3f23c8a9986ca3de8654f7ec5f758161ae" + "revision" : "9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf" } }, { diff --git a/Package.swift b/Package.swift index dcd248c..2885165 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "048cbf3f23c8a9986ca3de8654f7ec5f758161ae"), + revision: "9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 32226c1..fab7792 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/048cbf3f23c8a9986ca3de8654f7ec5f758161ae/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 62732a6f65205dd655ccd5d86fd9d6038bf1649e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:27:59 +0800 Subject: [PATCH 29/67] build: pin verified configuration core --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 774ffdb..f793261 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -667,7 +667,7 @@ current directory and user scope uses HOME. | 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/9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/6bb04bcb5d05cf1ac40ceb929a73fb5921768183/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index b10fc67..d4876b7 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/6bb04bcb5d05cf1ac40ceb929a73fb5921768183/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. diff --git a/Package.resolved b/Package.resolved index 2cbef28..06a85ef 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "e11990a3db11bc8b23269e077c217376ee1b0e435919dfea9c6b625dd2efdb33", + "originHash" : "25322fbce244b162bc4cb069b304c772a71a89f579ff229bbffa02185afa596e", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf" + "revision" : "6bb04bcb5d05cf1ac40ceb929a73fb5921768183" } }, { diff --git a/Package.swift b/Package.swift index 2885165..b1db9d1 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf"), + revision: "6bb04bcb5d05cf1ac40ceb929a73fb5921768183"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index fab7792..a6d72fc 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/9318c2a25e94e13c5cbf7d1a5464de2ec9cbaabf/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/6bb04bcb5d05cf1ac40ceb929a73fb5921768183/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From a4ee566e34ebad14b66b43bac4bd3e063bd59da6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:51:14 +0800 Subject: [PATCH 30/67] build: pin verified configuration core --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index f793261..d5e214e 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -667,7 +667,7 @@ current directory and user scope uses HOME. | 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/6bb04bcb5d05cf1ac40ceb929a73fb5921768183/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index d4876b7..8b49d79 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/6bb04bcb5d05cf1ac40ceb929a73fb5921768183/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf/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. diff --git a/Package.resolved b/Package.resolved index 06a85ef..82f91c3 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "25322fbce244b162bc4cb069b304c772a71a89f579ff229bbffa02185afa596e", + "originHash" : "fc7efeab50795f0526bb425bf2caa7e50f121098fc60a85933a2f758fa31e4dd", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "6bb04bcb5d05cf1ac40ceb929a73fb5921768183" + "revision" : "0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf" } }, { diff --git a/Package.swift b/Package.swift index b1db9d1..1a71736 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "6bb04bcb5d05cf1ac40ceb929a73fb5921768183"), + revision: "0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index a6d72fc..3629fa2 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/6bb04bcb5d05cf1ac40ceb929a73fb5921768183/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 2d09f33643d76c6bd3444c2261f25be6482ec388 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:02:48 +0800 Subject: [PATCH 31/67] build: pin verified configuration core --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index d5e214e..1b00d90 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -667,7 +667,7 @@ current directory and user scope uses HOME. | 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/0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/52b2e1ed46ff8f3278961301db684d83e58ed485/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 8b49d79..2979606 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/52b2e1ed46ff8f3278961301db684d83e58ed485/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. diff --git a/Package.resolved b/Package.resolved index 82f91c3..d23b75e 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "fc7efeab50795f0526bb425bf2caa7e50f121098fc60a85933a2f758fa31e4dd", + "originHash" : "2b211d69bfe79f844c0948fce3daeb0082a4ea9478be5e83a7825d05e72ecfba", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf" + "revision" : "52b2e1ed46ff8f3278961301db684d83e58ed485" } }, { diff --git a/Package.swift b/Package.swift index 1a71736..4cb82c3 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf"), + revision: "52b2e1ed46ff8f3278961301db684d83e58ed485"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 3629fa2..6f858a9 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/0c1828cb9d0dcae7dd74d9e55d54d1a7496d0dbf/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/52b2e1ed46ff8f3278961301db684d83e58ed485/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 8d3ff90f2a359766421301260de1bfbcfe925796 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 20:50:19 +0800 Subject: [PATCH 32/67] feat: export locked component inventory from the CLI --- Documentation/Reference/CLI.md | 9 ++++- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 +- Package.swift | 2 +- README.md | 2 +- Sources/CLI/ComponentCommands.swift | 17 ++++++++- Tests/CLITests/ComponentExecutableTests.swift | 37 ++++++++++++++++++- 7 files changed, 65 insertions(+), 8 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 1b00d90..c70f432 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -27,6 +27,7 @@ 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 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] @@ -285,6 +286,12 @@ schema ownership. ## Components +Use `agents components inventory > inventory.cdx.json` to export the current project's +locked components as CycloneDX 1.6 JSON. 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 @@ -667,7 +674,7 @@ current directory and user scope uses HOME. | 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/52b2e1ed46ff8f3278961301db684d83e58ed485/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/d01919bf77e2c465607304484e3abd9500aabb6f/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 2979606..d332f69 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/52b2e1ed46ff8f3278961301db684d83e58ed485/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/d01919bf77e2c465607304484e3abd9500aabb6f/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. diff --git a/Package.resolved b/Package.resolved index d23b75e..8abf906 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "2b211d69bfe79f844c0948fce3daeb0082a4ea9478be5e83a7825d05e72ecfba", + "originHash" : "612f41d9a8604719ea8c23aaa11e879159ef0732029374df6caf2fbbb6775645", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "52b2e1ed46ff8f3278961301db684d83e58ed485" + "revision" : "d01919bf77e2c465607304484e3abd9500aabb6f" } }, { diff --git a/Package.swift b/Package.swift index 4cb82c3..c9a1eb6 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "52b2e1ed46ff8f3278961301db684d83e58ed485"), + revision: "d01919bf77e2c465607304484e3abd9500aabb6f"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 6f858a9..303a862 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/52b2e1ed46ff8f3278961301db684d83e58ed485/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/d01919bf77e2c465607304484e3abd9500aabb6f/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. diff --git a/Sources/CLI/ComponentCommands.swift b/Sources/CLI/ComponentCommands.swift index acd082d..e86d5e1 100644 --- a/Sources/CLI/ComponentCommands.swift +++ b/Sources/CLI/ComponentCommands.swift @@ -7,7 +7,22 @@ struct ComponentsCommand: ParsableCommand { static let configuration = CommandConfiguration( commandName: "components", abstract: "Inspect, add and remove managed components.", - subcommands: [ListComponents.self, AddComponents.self, RemoveComponents.self]) + 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 JSON.") + @OptionGroup var location: ScopeOptions + + func run() throws { + let inspection = try UpdateOperations.inspect(scope: location.scope) + let data = try inspection.cycloneDXInventory() + try FileHandle.standardOutput.write(contentsOf: data + Data("\n".utf8)) + } } /// Builds canonical group intent; source parsing and graph discovery remain in Core. diff --git a/Tests/CLITests/ComponentExecutableTests.swift b/Tests/CLITests/ComponentExecutableTests.swift index 752ef27..a66bba2 100644 --- a/Tests/CLITests/ComponentExecutableTests.swift +++ b/Tests/CLITests/ComponentExecutableTests.swift @@ -32,6 +32,15 @@ struct ComponentExecutableTests { 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() @@ -56,6 +65,30 @@ struct ComponentExecutableTests { "# 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 { $0["name"] as? String == fixture.source.lastPathComponent }) + 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( @@ -85,7 +118,9 @@ struct ComponentExecutableTests { let pending = fixture.state("transaction.new") try Data("pending".utf8).write(to: pending) let before = try Data(contentsOf: pending) - for command in [["components", "list"], ["mcp", "test", "server"]] { + 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) From 07a1ae379e1552b6eed97452001eabcb076c4bdf Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:36:25 +0800 Subject: [PATCH 33/67] feat: manage registry servers and distributable packages --- Documentation/Reference/CLI.md | 52 ++++- Documentation/Reference/ManifestDump.md | 2 +- .../Reference/Schemas/doctor.schema.json | 3 +- .../Schemas/mcp-registry-page.schema.json | 23 ++ .../Schemas/mcp-registry-server.schema.json | 86 +++++++ Package.resolved | 4 +- Package.swift | 2 +- README.md | 2 +- Sources/CLI/BindingOptions.swift | 8 +- Sources/CLI/BundleCommands.swift | 102 +++++++++ Sources/CLI/EntryPoint.swift | 3 +- Sources/CLI/JSONReports.swift | 27 ++- Sources/CLI/LifecycleCommands.swift | 19 +- Sources/CLI/MCPCommand.swift | 3 +- Sources/CLI/MCPRegistryCommands.swift | 212 ++++++++++++++++++ Sources/CLI/MarketplaceCommands.swift | 138 ++++++++++++ Sources/CLI/PolicyCommand.swift | 56 +++++ 17 files changed, 722 insertions(+), 20 deletions(-) create mode 100644 Documentation/Reference/Schemas/mcp-registry-page.schema.json create mode 100644 Documentation/Reference/Schemas/mcp-registry-server.schema.json create mode 100644 Sources/CLI/BundleCommands.swift create mode 100644 Sources/CLI/MCPRegistryCommands.swift create mode 100644 Sources/CLI/MarketplaceCommands.swift create mode 100644 Sources/CLI/PolicyCommand.swift diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index c70f432..2c60b62 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -32,11 +32,22 @@ agents components list [ --group --alias ] [--json] [--sc 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 export --name --package-version --component … [--scope ] +agents bundle inspect +agents bundle import --agent … [--component ] [--scope ] [--json | --apply] +agents marketplace publish --directory [--summary ] +agents marketplace search [] (--directory | --git [--ref ] [--subpath ]) +agents marketplace install --directory --agent … [--package-version ] [--alias ] [--json | --apply] +agents marketplace installed [--scope ] +agents marketplace remove [--scope ] [--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 install [--json] [--binding NAME=ENV_VAR] agents update [--apply | --json] [--binding NAME=ENV_VAR] [--replace] [--changing-access] -agents doctor [--root

…] [--json] +agents doctor [--root …] [--ci] [--json] ``` `agents --help`, `agents skills --help`, `agents instructions --help`, @@ -343,6 +354,19 @@ 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. +## MCP Registry + +Use `mcp search` to browse the public registry, then `mcp show` to inspect an exact version, +its numbered installation choices and input requirements. Pass `--registry ` +to use a private registry and `--token-env ` when it needs 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` @@ -662,7 +686,7 @@ 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 every managed kind. +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. 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 @@ -674,7 +698,7 @@ current directory and user scope uses HOME. | 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/d01919bf77e2c465607304484e3abd9500aabb6f/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/427d231cc1f178dd1afd8ded55b1129fe28bbbe5/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 @@ -820,6 +844,9 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | `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` | | `mcp test --json` | [MCP test](Schemas/mcp-test.schema.json) | `schemaVersion`, `kind`, `transport`, `outcome`, `cleanupComplete`, `elapsed`, `tools` | An empty installed list: @@ -903,3 +930,22 @@ 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 + +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 index d332f69..c4792a8 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/d01919bf77e2c465607304484e3abd9500aabb6f/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/427d231cc1f178dd1afd8ded55b1129fe28bbbe5/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. diff --git a/Documentation/Reference/Schemas/doctor.schema.json b/Documentation/Reference/Schemas/doctor.schema.json index da526af..0d6c88f 100644 --- a/Documentation/Reference/Schemas/doctor.schema.json +++ b/Documentation/Reference/Schemas/doctor.schema.json @@ -52,7 +52,8 @@ "enum": [ "skills", "instructions", - "components" + "components", + "sourcePolicy" ] } }, 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/Package.resolved b/Package.resolved index 8abf906..7bce032 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "612f41d9a8604719ea8c23aaa11e879159ef0732029374df6caf2fbbb6775645", + "originHash" : "85f8fb929c04e5f93a42dd4273b90b90b3d798d6eabbcf5b55858715177051b1", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "d01919bf77e2c465607304484e3abd9500aabb6f" + "revision" : "427d231cc1f178dd1afd8ded55b1129fe28bbbe5" } }, { diff --git a/Package.swift b/Package.swift index c9a1eb6..c061f71 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "d01919bf77e2c465607304484e3abd9500aabb6f"), + revision: "427d231cc1f178dd1afd8ded55b1129fe28bbbe5"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 303a862..32e9089 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/d01919bf77e2c465607304484e3abd9500aabb6f/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/427d231cc1f178dd1afd8ded55b1129fe28bbbe5/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. diff --git a/Sources/CLI/BindingOptions.swift b/Sources/CLI/BindingOptions.swift index 02eaf11..dadaf2d 100644 --- a/Sources/CLI/BindingOptions.swift +++ b/Sources/CLI/BindingOptions.swift @@ -14,6 +14,10 @@ struct BindingOptions: ParsableArguments { 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 { @@ -22,10 +26,10 @@ struct BindingOptions: ParsableArguments { mapping.utf8.count <= 4096, !mapping.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains), !parts[1].contains("="), variables[String(parts[0])] == nil - else { throw ValidationError("Use distinct --binding NAME=ENV_VAR mappings") } + else { throw ValidationError("Use distinct \(option) NAME=ENV_VAR mappings") } variables[String(parts[0])] = String(parts[1]) } - return EnvironmentBindings(variables: variables) + return variables } } diff --git a/Sources/CLI/BundleCommands.swift b/Sources/CLI/BundleCommands.swift new file mode 100644 index 0000000..16e8f8a --- /dev/null +++ b/Sources/CLI/BundleCommands.swift @@ -0,0 +1,102 @@ +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: [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] + @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 data = try BundleOperations.export( + BundlePackage(name: name, version: packageVersion), 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 component in bundle.components { + Terminal.write( + "\(Terminal.line(component.id)) \(component.kind.rawValue) \(Terminal.line(component.name))\n" + ) + } + } +} + +struct ImportBundle: ParsableCommand { + 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() throws { + let bundle = try BundleOperations.inspect(Data(contentsOf: URL(fileURLWithPath: file))) + let preview = try BundleOperations.previewImport( + bundle, selections: installation.selections(in: bundle), + scope: installation.options.location.scope, environment: RuntimeEnvironment(), + replace: installation.replace) + try installation.finish(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) } + } + + func finish(_ preview: BundleImportPreview) throws { + 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.apply { + _ = try BundleOperations.withPreparedImport(preview, bindingProvider: bindings.provider()) { + try $0.apply() + } + } else if !options.json { + options.previewNotice(changed: preview.report.hasChanges) + } + } +} diff --git a/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index d849a1f..b886025 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -28,7 +28,8 @@ struct Agents: ParsableCommand { """, subcommands: [ Skills.self, InstructionsCommand.self, Watch.self, Manifest.self, Install.self, Update.self, - Doctor.self, ComponentsCommand.self, ImportCommand.self, MCPCommand.self, + Doctor.self, ComponentsCommand.self, ImportCommand.self, MCPCommand.self, BundleCommand.self, + MarketplaceCommand.self, PolicyCommand.self, ] ) diff --git a/Sources/CLI/JSONReports.swift b/Sources/CLI/JSONReports.swift index 193b717..3e43625 100644 --- a/Sources/CLI/JSONReports.swift +++ b/Sources/CLI/JSONReports.swift @@ -233,14 +233,16 @@ struct DoctorRoot: Encodable { init( root: String, scope: String, report: DoctorReport, instructions: InstructionDoctorReport, - environment: RuntimeEnvironment, inventory: ScopeInspection? = nil + 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" } } } @@ -252,11 +254,12 @@ 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 = - ["pending-recovery", "unresolved-transaction"].contains(check.id) + (["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" @@ -264,13 +267,15 @@ struct CheckItem: Encodable { 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, .unresolvedTransaction: status = "error" + case .drift, .missingTarget, .missingLock, .ownChanged: + status = ci ? "error" : "warning" default: status = "warning" } @@ -281,6 +286,16 @@ 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(kind: String, id: String, status: String, message: String, path: String?) { self.kind = kind self.id = id diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index 24d7b52..403a4e8 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -166,6 +166,8 @@ 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: "Print the versioned JSON report.") var json = false func validate() throws { @@ -196,11 +198,26 @@ struct Doctor: ParsableCommand { 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 audit = try SourcePolicyOperations.audit(scope: location.scope, environment: runtime) + policyChecks = audit.violations.map(CheckItem.init) + } 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, inventory: inventory)) + environment: runtime, inventory: inventory, policyChecks: policyChecks, ci: ci)) } let report = DoctorOutput(roots: reports) if json { diff --git a/Sources/CLI/MCPCommand.swift b/Sources/CLI/MCPCommand.swift index cf1c4fc..9f88b7b 100644 --- a/Sources/CLI/MCPCommand.swift +++ b/Sources/CLI/MCPCommand.swift @@ -6,7 +6,8 @@ import Foundation struct MCPCommand: ParsableCommand { static let configuration = CommandConfiguration( commandName: "mcp", - abstract: "Explicitly test a managed MCP connection.", subcommands: [TestMCP.self]) + abstract: "Discover, configure and test MCP servers.", + subcommands: [SearchMCP.self, ShowMCP.self, AddRegistryMCP.self, TestMCP.self]) } struct TestMCP: AsyncParsableCommand { diff --git a/Sources/CLI/MCPRegistryCommands.swift b/Sources/CLI/MCPRegistryCommands.swift new file mode 100644 index 0000000..f916d9b --- /dev/null +++ b/Sources/CLI/MCPRegistryCommands.swift @@ -0,0 +1,212 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct RegistryOptions: ParsableArguments { + @Option(help: "MCP Registry v0.1 base URL. Defaults to the public MCP Registry.") + 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 .official } + 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 + @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()) + 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() async throws -> MCPRegistryServer { + try await connection.client().server( + named: server, version: serverVersion, credentials: connection.credentials()) + } +} + +struct ShowMCP: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "show", abstract: "Inspect a registry server and its installation choices.") + @OptionGroup var selection: RegistryServerOptions + @Flag(help: "Print the JSON result.") var json = false + + mutating func run() async throws { + let report = try await RegistryServerReport(selection.load()) + 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() + 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/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift new file mode 100644 index 0000000..b0a1884 --- /dev/null +++ b/Sources/CLI/MarketplaceCommands.swift @@ -0,0 +1,138 @@ +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: [ + SearchMarketplace.self, PublishPackage.self, InstallMarketPackage.self, + InstalledPackages.self, RemoveMarketPackage.self, + ]) +} + +struct CatalogOptions: ParsableArguments { + @Option(help: "Existing team marketplace directory.") var directory: 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? + + func catalog() throws -> MarketplaceCatalog { + let origin: MarketplaceOrigin + switch (directory, git) { + case (let path?, nil) where ref == nil && subpath == nil: + origin = try MarketplaceOrigin( + kind: .directory, location: URL(fileURLWithPath: path).standardizedFileURL.path) + case (nil, let repository?): + origin = try MarketplaceOrigin(kind: .git, location: repository, ref: ref, subpath: subpath) + default: + throw ValidationError( + "Specify either --directory or --git; --ref and --subpath require --git") + } + return try MarketplaceOperations.browse( + MarketplaceRegistration(name: "catalog", origin: origin)) + } +} + +struct SearchMarketplace: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "search", abstract: "List package releases by name or summary.") + @Argument(help: "Optional package name or summary text.") var query: String? + @OptionGroup var source: CatalogOptions + + func run() throws { + let releases = try source.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 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 + @Option(help: "Existing marketplace directory.") var directory: String + @Option(help: "Short description for the catalog.") var summary: String? + + func run() throws { + let published = try MarketplaceOperations.publishBundle( + Data(contentsOf: URL(fileURLWithPath: archive)), to: URL(fileURLWithPath: directory), + summary: summary) + Terminal.write( + "\(Terminal.line(published.coordinate.package)) \(Terminal.line(published.coordinate.version)) \(published.archiveDigest)\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 pins = try MarketplaceOperations.installed(scope: location.scope) + 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 pins.isEmpty { Terminal.write("No marketplace packages installed.\n") } + } +} + +struct InstallMarketPackage: ParsableCommand { + 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 + @Option(help: "Exact release. Omit to select the latest version.") var packageVersion: String? + @Option(help: "Name for this dependency in the declaration. Defaults to its package name.") + var alias: String? + @OptionGroup var source: CatalogOptions + @OptionGroup var installation: BundleInstallOptions + + func run() throws { + let release = try source.catalog().select(package: package, version: packageVersion) + let verified = try MarketplaceOperations.acquire(release) + let contents = try verified.inspectBundle() + let preview = try verified.previewImport( + as: alias ?? package, selections: installation.selections(in: contents), + scope: installation.options.location.scope, replace: installation.replace) + try installation.finish(preview) + } +} + +struct RemoveMarketPackage: ParsableCommand { + 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 + @OptionGroup var options: UpdateOptions + @OptionGroup var bindings: BindingOptions + + func run() throws { + let request = MarketplaceOperations.removalRequest(for: name) + let scope = options.location.scope + let report = try UpdateOperations.preview(request, scope: scope) + if options.json { + try Terminal.json(UpdateReport(report)) + } else { + Terminal.updateDifferences(report, paths: options.location.paths) + } + if options.apply { + _ = try withRecovery { + try UpdateOperations.withPreparedUpdate( + request, scope: scope, bindingProvider: bindings.provider() + ) { + try $0.apply(ifUnchangedFrom: report.displayedFingerprint) + } + } + } else if !options.json { + options.previewNotice(changed: report.hasChanges) + } + } +} diff --git a/Sources/CLI/PolicyCommand.swift b/Sources/CLI/PolicyCommand.swift new file mode 100644 index 0000000..a051ef7 --- /dev/null +++ b/Sources/CLI/PolicyCommand.swift @@ -0,0 +1,56 @@ +import AgentsCore +import AgentsManifest +import AgentsUpdates +import ArgumentParser +import Foundation + +struct PolicyCommand: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "policy", abstract: "Inspect and configure allowed sources.", + subcommands: [ShowSourcePolicy.self, SetSourcePolicy.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") + } + } +} From bb9c042e39f3dc89f6086cb74f538b16251e310e Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 21:55:09 +0800 Subject: [PATCH 34/67] feat: report package lock drift and preview exact release changes --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- .../Reference/Schemas/doctor.schema.json | 3 +- .../Reference/Schemas/update.schema.json | 54 +++++++++++++++++++ Package.resolved | 4 +- Package.swift | 2 +- README.md | 2 +- Sources/CLI/JSONReports.swift | 36 ++++++++++++- Sources/CLI/MCPRegistryCommands.swift | 12 +++-- Sources/CLI/MarketplaceCommands.swift | 12 +++-- Sources/CLI/Terminal.swift | 9 ++++ 11 files changed, 120 insertions(+), 18 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 2c60b62..af64b92 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -698,7 +698,7 @@ current directory and user scope uses HOME. | 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/427d231cc1f178dd1afd8ded55b1129fe28bbbe5/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/b50a58927c71fb38aa5cd62a349c77278ba786e5/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index c4792a8..488be09 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/427d231cc1f178dd1afd8ded55b1129fe28bbbe5/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/b50a58927c71fb38aa5cd62a349c77278ba786e5/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. diff --git a/Documentation/Reference/Schemas/doctor.schema.json b/Documentation/Reference/Schemas/doctor.schema.json index 0d6c88f..1a2d585 100644 --- a/Documentation/Reference/Schemas/doctor.schema.json +++ b/Documentation/Reference/Schemas/doctor.schema.json @@ -53,7 +53,8 @@ "skills", "instructions", "components", - "sourcePolicy" + "sourcePolicy", + "marketplace" ] } }, diff --git a/Documentation/Reference/Schemas/update.schema.json b/Documentation/Reference/Schemas/update.schema.json index 075ceb9..205fd5c 100644 --- a/Documentation/Reference/Schemas/update.schema.json +++ b/Documentation/Reference/Schemas/update.schema.json @@ -117,6 +117,38 @@ "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": [ @@ -209,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 7bce032..01275a3 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "85f8fb929c04e5f93a42dd4273b90b90b3d798d6eabbcf5b55858715177051b1", + "originHash" : "2570d67515bc997e188e6dfd02f2e07c455c2a9873267db94cb94955b5f40720", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "427d231cc1f178dd1afd8ded55b1129fe28bbbe5" + "revision" : "b50a58927c71fb38aa5cd62a349c77278ba786e5" } }, { diff --git a/Package.swift b/Package.swift index c061f71..3991b73 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "427d231cc1f178dd1afd8ded55b1129fe28bbbe5"), + revision: "b50a58927c71fb38aa5cd62a349c77278ba786e5"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 32e9089..7410744 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/427d231cc1f178dd1afd8ded55b1129fe28bbbe5/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/b50a58927c71fb38aa5cd62a349c77278ba786e5/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. diff --git a/Sources/CLI/JSONReports.swift b/Sources/CLI/JSONReports.swift index 3e43625..881068d 100644 --- a/Sources/CLI/JSONReports.swift +++ b/Sources/CLI/JSONReports.swift @@ -74,6 +74,7 @@ struct UpdateReport: Encodable { let skills: [UpdateItem] let instructions: InstructionChanges? + let marketplaceChanges: [PackagePinChange]? let lockMissing: Bool? let components: [ComponentChangeItem]? @@ -82,6 +83,7 @@ struct UpdateReport: Encodable { changed = results.contains(where: \.changed) skills = results.map(UpdateItem.init) instructions = nil + marketplaceChanges = nil lockMissing = nil components = nil } @@ -91,11 +93,39 @@ 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) + } +} + struct UpdateItem: Encodable { let name: String let source: String @@ -323,7 +353,11 @@ struct CheckItem: Encodable { } let owners = Set( inspection.components.filter { $0.kind != .skills && $0.kind != .instructions }.map(\.record)) - return inspection.deployments.filter { !owners.isDisjoint(with: $0.ownerRecords) }.map { + 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)] + } ?? [] + return packageChecks + 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)", diff --git a/Sources/CLI/MCPRegistryCommands.swift b/Sources/CLI/MCPRegistryCommands.swift index f916d9b..967e23b 100644 --- a/Sources/CLI/MCPRegistryCommands.swift +++ b/Sources/CLI/MCPRegistryCommands.swift @@ -29,6 +29,7 @@ struct SearchMCP: AsyncParsableCommand { 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 @@ -37,7 +38,7 @@ struct SearchMCP: AsyncParsableCommand { mutating func run() async throws { let page = try await connection.client().search( query, version: allVersions ? nil : "latest", limit: limit, cursor: cursor, - credentials: connection.credentials()) + credentials: connection.credentials(), scope: location.scope) if json { try Terminal.json( RegistryPageReport( @@ -59,9 +60,9 @@ struct RegistryServerOptions: ParsableArguments { @Option(help: "Published server version, or latest.") var serverVersion = "latest" @OptionGroup var connection: RegistryOptions - func load() async throws -> MCPRegistryServer { + func load(in scope: InstallScope) async throws -> MCPRegistryServer { try await connection.client().server( - named: server, version: serverVersion, credentials: connection.credentials()) + named: server, version: serverVersion, credentials: connection.credentials(), scope: scope) } } @@ -69,10 +70,11 @@ 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()) + let report = try await RegistryServerReport(selection.load(in: location.scope)) if json { try Terminal.json(report) return @@ -164,7 +166,7 @@ struct AddRegistryMCP: AsyncParsableCommand { @Option(help: "Console command provided by the selected package.") var packageCommand: String? mutating func run() async throws { - let server = try await selection.load() + 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") diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift index b0a1884..17ef88d 100644 --- a/Sources/CLI/MarketplaceCommands.swift +++ b/Sources/CLI/MarketplaceCommands.swift @@ -18,7 +18,7 @@ struct CatalogOptions: ParsableArguments { @Option(help: "Git ref to browse.") var ref: String? @Option(help: "Marketplace directory within the Git repository.") var subpath: String? - func catalog() throws -> MarketplaceCatalog { + func catalog(in scope: InstallScope) throws -> MarketplaceCatalog { let origin: MarketplaceOrigin switch (directory, git) { case (let path?, nil) where ref == nil && subpath == nil: @@ -31,18 +31,19 @@ struct CatalogOptions: ParsableArguments { "Specify either --directory or --git; --ref and --subpath require --git") } return try MarketplaceOperations.browse( - MarketplaceRegistration(name: "catalog", origin: origin)) + MarketplaceRegistration(name: "catalog", origin: origin), scope: scope) } } struct SearchMarketplace: ParsableCommand { static let configuration = CommandConfiguration( commandName: "search", abstract: "List package releases by name or summary.") + @OptionGroup var location: ScopeOptions @Argument(help: "Optional package name or summary text.") var query: String? @OptionGroup var source: CatalogOptions func run() throws { - let releases = try source.catalog().search(query ?? "") + let releases = try source.catalog(in: location.scope).search(query ?? "") for release in releases { Terminal.write( "\(Terminal.line(release.coordinate.package)) \(Terminal.line(release.coordinate.version)) \(Terminal.line(release.summary ?? ""))\n" @@ -97,8 +98,9 @@ struct InstallMarketPackage: ParsableCommand { @OptionGroup var installation: BundleInstallOptions func run() throws { - let release = try source.catalog().select(package: package, version: packageVersion) - let verified = try MarketplaceOperations.acquire(release) + let scope = installation.options.location.scope + let release = try source.catalog(in: scope).select(package: package, version: packageVersion) + let verified = try MarketplaceOperations.acquire(release, scope: scope) let contents = try verified.inspectBundle() let preview = try verified.previewImport( as: alias ?? package, selections: installation.selections(in: contents), diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 06f91a5..7b3781e 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -348,6 +348,15 @@ enum Terminal { 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 missingSkillLock(report.lockMissing && !skills.isEmpty) From c9bcd7941ad58f7c0b914e77bc3c38ac8f3abbb8 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:08:50 +0800 Subject: [PATCH 35/67] feat: check for package upgrades and export inventories for CI --- Documentation/Reference/CLI.md | 10 ++-- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 +- Package.swift | 2 +- README.md | 2 +- Sources/CLI/BundleCommands.swift | 16 ++++-- Sources/CLI/ComponentCommands.swift | 23 +++++++-- Sources/CLI/LifecycleCommands.swift | 14 ++++- Sources/CLI/MarketplaceCommands.swift | 68 ++++++++++++++++++++++++- 9 files changed, 122 insertions(+), 19 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index af64b92..232f9c0 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -39,6 +39,8 @@ agents marketplace publish --directory [--summary ] agents marketplace search [] (--directory | --git [--ref ] [--subpath ]) agents marketplace install --directory --agent … [--package-version ] [--alias ] [--json | --apply] agents marketplace installed [--scope ] +agents marketplace outdated [] [--scope ] +agents marketplace upgrade [--package-version ] [--scope ] [--apply] [--json] agents marketplace remove [--scope ] [--json | --apply] agents mcp search [] [--registry ] [--limit ] [--cursor ] [--all-versions] [--json] agents mcp show [--server-version ] [--registry ] [--json] @@ -47,7 +49,7 @@ agents mcp test [--kind mcpServer] [--identity ] [--occurrence ] agents manifest dump --json [--scope project|user] agents install [--json] [--binding NAME=ENV_VAR] agents update [--apply | --json] [--binding NAME=ENV_VAR] [--replace] [--changing-access] -agents doctor [--root …] [--ci] [--json] +agents doctor [--root …] [--ci] [--require-organization-policy] [--json] ``` `agents --help`, `agents skills --help`, `agents instructions --help`, @@ -298,7 +300,7 @@ schema ownership. ## Components Use `agents components inventory > inventory.cdx.json` to export the current project's -locked components as CycloneDX 1.6 JSON. Pass `--scope user` for user configuration. +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. @@ -686,7 +688,7 @@ 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 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. The audit checks locked sources against each applicable source policy. A violation or an unreadable policy produces an error and exit status 1. +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 the policy identified by `AGENTS_ORGANIZATION_SOURCE_POLICY`. 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 @@ -698,7 +700,7 @@ current directory and user scope uses HOME. | 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/b50a58927c71fb38aa5cd62a349c77278ba786e5/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/89d8f0a74b87a1fc846354499460fce8301ed076/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 488be09..7c10feb 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/b50a58927c71fb38aa5cd62a349c77278ba786e5/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/89d8f0a74b87a1fc846354499460fce8301ed076/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. diff --git a/Package.resolved b/Package.resolved index 01275a3..12aa9f4 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "2570d67515bc997e188e6dfd02f2e07c455c2a9873267db94cb94955b5f40720", + "originHash" : "05f895f211a3d6b973d60d8880fa2d025a2a34ecd0bdebf6f4aa4f0f38abfff8", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "b50a58927c71fb38aa5cd62a349c77278ba786e5" + "revision" : "89d8f0a74b87a1fc846354499460fce8301ed076" } }, { diff --git a/Package.swift b/Package.swift index 3991b73..223a269 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "b50a58927c71fb38aa5cd62a349c77278ba786e5"), + revision: "89d8f0a74b87a1fc846354499460fce8301ed076"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 7410744..402f8a6 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/b50a58927c71fb38aa5cd62a349c77278ba786e5/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/89d8f0a74b87a1fc846354499460fce8301ed076/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. diff --git a/Sources/CLI/BundleCommands.swift b/Sources/CLI/BundleCommands.swift index 16e8f8a..14ece77 100644 --- a/Sources/CLI/BundleCommands.swift +++ b/Sources/CLI/BundleCommands.swift @@ -85,18 +85,24 @@ struct BundleInstallOptions: ParsableArguments { } func finish(_ preview: BundleImportPreview) throws { - if options.json { + try options.finishImport(preview, bindings: bindings) + } +} + +extension UpdateOptions { + func finishImport(_ preview: BundleImportPreview, bindings: BindingOptions) throws { + if json { try Terminal.json(UpdateReport(preview.report)) } else { - Terminal.updateDifferences(preview.report, paths: options.location.paths) + Terminal.updateDifferences(preview.report, paths: location.paths) } if let conflict = preview.ownershipConflict { throw CoreError.invalidState(conflict) } - if options.apply { + if apply { _ = try BundleOperations.withPreparedImport(preview, bindingProvider: bindings.provider()) { try $0.apply() } - } else if !options.json { - options.previewNotice(changed: preview.report.hasChanges) + } else if !json { + previewNotice(changed: preview.report.hasChanges) } } } diff --git a/Sources/CLI/ComponentCommands.swift b/Sources/CLI/ComponentCommands.swift index e86d5e1..b0dc4c1 100644 --- a/Sources/CLI/ComponentCommands.swift +++ b/Sources/CLI/ComponentCommands.swift @@ -15,12 +15,29 @@ struct ComponentsCommand: ParsableCommand { struct ComponentInventoryCommand: ParsableCommand { static let configuration = CommandConfiguration( - commandName: "inventory", abstract: "Export the locked component inventory as CycloneDX JSON.") + 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 inspection = try UpdateOperations.inspect(scope: location.scope) - let data = try inspection.cycloneDXInventory() + 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)) } } diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index 403a4e8..aeed091 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -168,6 +168,8 @@ struct Doctor: ParsableCommand { 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 { @@ -204,7 +206,17 @@ struct Doctor: ParsableCommand { } else { do { let audit = try SourcePolicyOperations.audit(scope: location.scope, environment: runtime) - policyChecks = audit.violations.map(CheckItem.init) + var checks = audit.violations.map(CheckItem.init) + if requireOrganizationPolicy + && !audit.policy.effective.layers.contains(where: { $0.scope == .organization }) + { + checks.append( + CheckItem( + kind: "sourcePolicy", id: "missingOrganizationPolicy", status: "error", + message: "Set AGENTS_ORGANIZATION_SOURCE_POLICY to the organization policy file.", + path: nil)) + } + policyChecks = checks } catch { policyChecks = [ CheckItem( diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift index 17ef88d..43014e5 100644 --- a/Sources/CLI/MarketplaceCommands.swift +++ b/Sources/CLI/MarketplaceCommands.swift @@ -8,7 +8,8 @@ struct MarketplaceCommand: ParsableCommand { commandName: "marketplace", abstract: "Browse team packages and manage their releases.", subcommands: [ SearchMarketplace.self, PublishPackage.self, InstallMarketPackage.self, - InstalledPackages.self, RemoveMarketPackage.self, + InstalledPackages.self, OutdatedPackages.self, UpgradeMarketPackage.self, + RemoveMarketPackage.self, ]) } @@ -87,6 +88,71 @@ struct InstalledPackages: ParsableCommand { } } +struct OutdatedPackages: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "outdated", abstract: "Check installed packages for newer releases.") + @OptionGroup var location: ScopeOptions + @Argument(help: "Installed dependency name. Omit to check all packages.") var name: String? + + func run() throws { + let installed = try MarketplaceOperations.installed(scope: location.scope) + let pins = installed.filter { name == nil || name == $0.dependency.name } + if let name, pins.isEmpty { throw MarketplaceError.missingPin(name) } + for pin in pins { + let newer = try MarketplaceOperations.availableUpdates(for: pin, scope: location.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" + ) + } + if pins.isEmpty { Terminal.write("No marketplace packages installed.\n") } + } +} + +struct UpgradeMarketPackage: ParsableCommand { + 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 + @Option(help: "Newer release to select. Defaults to the newest available version.") + var packageVersion: String? + @OptionGroup var options: UpdateOptions + @OptionGroup var bindings: BindingOptions + + func run() throws { + let scope = options.location.scope + let inspection = try UpdateOperations.inspect(scope: scope) + try requireCommittedInspection(inspection) + 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: { + packageVersion == nil || $0.coordinate.version == packageVersion + }) + else { + if let 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 selections = try verified.inspectBundle().retainedSelections(for: pin, in: inspection) + guard !selections.isEmpty else { + throw ValidationError( + "No installed components match this release. Choose its components with marketplace install." + ) + } + let preview = try verified.previewImport(as: name, selections: selections, scope: scope) + try options.finishImport(preview, bindings: bindings) + } +} + struct InstallMarketPackage: ParsableCommand { static let configuration = CommandConfiguration( commandName: "install", abstract: "Preview or apply a marketplace release to this scope.") From ef52888556c0df3a166291310748caa1485eb019 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:29:14 +0800 Subject: [PATCH 36/67] feat: manage named marketplaces from the CLI --- Documentation/Reference/CLI.md | 11 ++-- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 +- Package.swift | 2 +- README.md | 2 +- Sources/CLI/MarketplaceCommands.swift | 77 ++++++++++++++++++++++--- 6 files changed, 81 insertions(+), 17 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 232f9c0..7872107 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -35,9 +35,12 @@ agents import --format [--root ] [--select --name --package-version --component … [--scope ] agents bundle inspect agents bundle import --agent … [--component ] [--scope ] [--json | --apply] -agents marketplace publish --directory [--summary ] -agents marketplace search [] (--directory | --git [--ref ] [--subpath ]) -agents marketplace install --directory --agent … [--package-version ] [--alias ] [--json | --apply] +agents marketplace publish (--directory | --catalog ) [--summary ] +agents marketplace register (--directory | --git [--ref ] [--subpath ]) [--scope ] +agents marketplace list [--scope ] +agents marketplace unregister [--scope ] +agents marketplace search [] (--catalog | --directory | --git [--ref ] [--subpath ]) +agents marketplace install (--catalog | --directory | --git ) --agent … [--package-version ] [--alias ] [--json | --apply] agents marketplace installed [--scope ] agents marketplace outdated [] [--scope ] agents marketplace upgrade [--package-version ] [--scope ] [--apply] [--json] @@ -700,7 +703,7 @@ current directory and user scope uses HOME. | 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/89d8f0a74b87a1fc846354499460fce8301ed076/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/dd030d9dcb12ce436ee548478c1939bde7402de8/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 7c10feb..f3be696 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/89d8f0a74b87a1fc846354499460fce8301ed076/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/dd030d9dcb12ce436ee548478c1939bde7402de8/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. diff --git a/Package.resolved b/Package.resolved index 12aa9f4..1192d52 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "05f895f211a3d6b973d60d8880fa2d025a2a34ecd0bdebf6f4aa4f0f38abfff8", + "originHash" : "106910657138cbdab8567b577188a73886237cad8676ec0ad275ee565ce53000", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "89d8f0a74b87a1fc846354499460fce8301ed076" + "revision" : "dd030d9dcb12ce436ee548478c1939bde7402de8" } }, { diff --git a/Package.swift b/Package.swift index 223a269..65832f1 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "89d8f0a74b87a1fc846354499460fce8301ed076"), + revision: "dd030d9dcb12ce436ee548478c1939bde7402de8"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 402f8a6..9d3214d 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/89d8f0a74b87a1fc846354499460fce8301ed076/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/dd030d9dcb12ce436ee548478c1939bde7402de8/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. diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift index 43014e5..4220dae 100644 --- a/Sources/CLI/MarketplaceCommands.swift +++ b/Sources/CLI/MarketplaceCommands.swift @@ -7,6 +7,7 @@ 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, PublishPackage.self, InstallMarketPackage.self, InstalledPackages.self, OutdatedPackages.self, UpgradeMarketPackage.self, RemoveMarketPackage.self, @@ -19,23 +20,78 @@ struct CatalogOptions: ParsableArguments { @Option(help: "Git ref to browse.") var ref: String? @Option(help: "Marketplace directory within the Git repository.") var subpath: String? - func catalog(in scope: InstallScope) throws -> MarketplaceCatalog { + @Option(help: "Registered marketplace name.") var catalog: String? + + func directOrigin(anchorDirectory: Bool = false) throws -> MarketplaceOrigin { + guard catalog == nil else { + throw ValidationError("Choose a directory or Git repository to register") + } let origin: MarketplaceOrigin switch (directory, git) { case (let path?, nil) where ref == nil && subpath == nil: origin = try MarketplaceOrigin( - kind: .directory, location: URL(fileURLWithPath: path).standardizedFileURL.path) + kind: .directory, + location: anchorDirectory ? URL(fileURLWithPath: path).standardizedFileURL.path : path) case (nil, let repository?): origin = try MarketplaceOrigin(kind: .git, location: repository, ref: ref, subpath: subpath) default: throw ValidationError( "Specify either --directory or --git; --ref and --subpath require --git") } - return try MarketplaceOperations.browse( - MarketplaceRegistration(name: "catalog", origin: origin), scope: scope) + return origin + } + + func registration(in scope: InstallScope) throws -> MarketplaceRegistration { + if let catalog { + guard directory == nil, git == 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)) + } + + func browse(in scope: InstallScope) throws -> MarketplaceCatalog { + try MarketplaceOperations.browse(registration(in: scope), scope: scope) + } +} + +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.") @@ -44,7 +100,7 @@ struct SearchMarketplace: ParsableCommand { @OptionGroup var source: CatalogOptions func run() throws { - let releases = try source.catalog(in: location.scope).search(query ?? "") + let releases = try source.browse(in: location.scope).search(query ?? "") for release in releases { Terminal.write( "\(Terminal.line(release.coordinate.package)) \(Terminal.line(release.coordinate.version)) \(Terminal.line(release.summary ?? ""))\n" @@ -58,12 +114,17 @@ 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 - @Option(help: "Existing marketplace directory.") var directory: 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: directory), + Data(contentsOf: URL(fileURLWithPath: archive)), to: URL(fileURLWithPath: address.location), summary: summary) Terminal.write( "\(Terminal.line(published.coordinate.package)) \(Terminal.line(published.coordinate.version)) \(published.archiveDigest)\n" @@ -165,7 +226,7 @@ struct InstallMarketPackage: ParsableCommand { func run() throws { let scope = installation.options.location.scope - let release = try source.catalog(in: scope).select(package: package, version: packageVersion) + let release = try source.browse(in: scope).select(package: package, version: packageVersion) let verified = try MarketplaceOperations.acquire(release, scope: scope) let contents = try verified.inspectBundle() let preview = try verified.previewImport( From 5f73c282db4497d648f2dc0c37e1d518d5811657 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:50:54 +0800 Subject: [PATCH 37/67] feat: configure Antigravity in CLI project and user scopes --- Documentation/Reference/CLI.md | 14 +++++++------- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 7 +++---- Sources/CLI/InstructionCommands.swift | 4 ++-- Sources/CLI/Options.swift | 4 ++-- Tests/CLITests/ExecutableTests.swift | 4 ++-- Tests/CLITests/InstructionExecutableTests.swift | 1 - Tests/CLITests/ParsingTests.swift | 10 ++++++++-- 10 files changed, 28 insertions(+), 24 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 7872107..4c15e78 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -82,8 +82,8 @@ 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 ` | 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 ` | @@ -92,8 +92,8 @@ Examples: | `--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`; `manifest dump` requires it | -Skill agents are `codex`, `claude-code`, `cursor`, `gemini-cli`, and `opencode`. -Instructions also accept `antigravity` in user scope. Cursor instructions use +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 @@ -217,8 +217,8 @@ 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. -Antigravity is a user-scope instruction recipient. Its app and `agy` read one -managed Markdown file per selected section under `~/.gemini/config/rules/`. +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 @@ -703,7 +703,7 @@ current directory and user scope uses HOME. | 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/dd030d9dcb12ce436ee548478c1939bde7402de8/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/420ad6b5a3891559a226e909a3f22c1a371b1ffc/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index f3be696..f35da7e 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/dd030d9dcb12ce436ee548478c1939bde7402de8/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/420ad6b5a3891559a226e909a3f22c1a371b1ffc/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. diff --git a/Package.resolved b/Package.resolved index 1192d52..864a743 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "106910657138cbdab8567b577188a73886237cad8676ec0ad275ee565ce53000", + "originHash" : "7b3f230610dde9e2a585227a4cc201ba95e0af9af5429a01ec6696f65a1b1fcb", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "dd030d9dcb12ce436ee548478c1939bde7402de8" + "revision" : "420ad6b5a3891559a226e909a3f22c1a371b1ffc" } }, { diff --git a/Package.swift b/Package.swift index 65832f1..ae84a9e 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "dd030d9dcb12ce436ee548478c1939bde7402de8"), + revision: "420ad6b5a3891559a226e909a3f22c1a371b1ffc"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 9d3214d..737b861 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/dd030d9dcb12ce436ee548478c1939bde7402de8/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/420ad6b5a3891559a226e909a3f22c1a371b1ffc/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. @@ -134,9 +134,8 @@ 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`. Use `--scope user --agent antigravity` -on `instructions add` to install the selected sections as individual Markdown -rules in `~/.gemini/config/rules/`. +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. diff --git a/Sources/CLI/InstructionCommands.swift b/Sources/CLI/InstructionCommands.swift index d54b9e7..9262654 100644 --- a/Sources/CLI/InstructionCommands.swift +++ b/Sources/CLI/InstructionCommands.swift @@ -19,7 +19,7 @@ struct InstructionAgentOptions: ParsableArguments { @Option( name: .long, help: - "Select recipients: codex, claude-code, cursor, gemini-cli, opencode, or antigravity. Repeat for several. Antigravity requires --scope user. Omit to use the configured default recipients.", + "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] = [] @@ -32,7 +32,7 @@ struct AddInstructions: ParsableCommand { static let configuration = CommandConfiguration( commandName: "add", abstract: "Declare and install instruction sections from a source.", discussion: - "With --agent antigravity --scope user, add the selected sections as global Antigravity rules. Other sections keep their recipients." + "With --agent antigravity, install the selected sections as rules in the selected scope. Other sections keep their recipients." ) @Argument( diff --git a/Sources/CLI/Options.swift b/Sources/CLI/Options.swift index 6765368..6d88089 100644 --- a/Sources/CLI/Options.swift +++ b/Sources/CLI/Options.swift @@ -22,7 +22,7 @@ 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.", + "Limit to this agent: codex, claude-code, cursor, gemini-cli, opencode, or antigravity. Repeat for several. Default: all recipients.", transform: parseSkillAgent) var agent: [AgentID] = [] @@ -35,7 +35,7 @@ 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.", + "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] = [] diff --git a/Tests/CLITests/ExecutableTests.swift b/Tests/CLITests/ExecutableTests.swift index bb34f90..693b258 100644 --- a/Tests/CLITests/ExecutableTests.swift +++ b/Tests/CLITests/ExecutableTests.swift @@ -427,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/InstructionExecutableTests.swift b/Tests/CLITests/InstructionExecutableTests.swift index be9555a..9d6b12d 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -695,7 +695,6 @@ struct InstructionExecutableTests { help.contains( "Select recipients: codex, claude-code, cursor, gemini-cli, opencode, or antigravity." )) - #expect(help.contains("Antigravity requires --scope user.")) #expect(help.contains("Omit to use the configured default recipients.")) } for command in [["add"], ["list"], ["remove"], ["update"], ["render", "chatgpt"]] { diff --git a/Tests/CLITests/ParsingTests.swift b/Tests/CLITests/ParsingTests.swift index d40b430..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"], @@ -116,8 +124,6 @@ struct ParsingTests { ["skills", "add", ".", "--from", "2.0.0", "--to", "1.0.0"], ["skills", "add", ".", "--mode", "edit", "--branch", "main"], ["skills", "list", "--scope", "global"], ["skills", "list", "--agent", "unknown"], - ["skills", "add", ".", "--agent", "antigravity"], - ["skills", "list", "--agent", "antigravity"], ["doctor", "--agent", "antigravity"], ["skills", "list", "--path", "skills"], ["skills", "list", "--full-depth"], ["install", "--agent", "codex"], ["install", "--mode", "copy"], ["install", "source"], ["update", "name"], ["update", "--apply", "--json"], From 9c634f3f146a2c525c2cf2fab5bb2f58885ec0fe Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:42:05 +0800 Subject: [PATCH 38/67] feat: add prompt content audit command --- Documentation/Reference/CLI.md | 53 +++++++++- Sources/CLI/AuditCommand.swift | 105 +++++++++++++++++++ Sources/CLI/EntryPoint.swift | 2 +- Tests/CLITests/AuditExecutableTests.swift | 118 ++++++++++++++++++++++ 4 files changed, 274 insertions(+), 4 deletions(-) create mode 100644 Sources/CLI/AuditCommand.swift create mode 100644 Tests/CLITests/AuditExecutableTests.swift diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 7872107..e49cbdc 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -2,9 +2,9 @@ `agents` manages declared agent components. Resolution, installation, state, and recovery operations use `AgentsCore`, `AgentsSkills`, and -`AgentsInstructions`; combined lifecycle, component inspection, import and MCP -tests use `AgentsUpdates`. `AgentsManifest` -owns declaration parsing and editing, and the manifest dump contract. +`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 @@ -53,6 +53,8 @@ agents manifest dump --json [--scope project|user] 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 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`, @@ -743,6 +745,51 @@ 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 Human-readable stdout is the default. Commands are non-interactive and never 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/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index b886025..7b1bbeb 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -29,7 +29,7 @@ struct Agents: ParsableCommand { subcommands: [ Skills.self, InstructionsCommand.self, Watch.self, Manifest.self, Install.self, Update.self, Doctor.self, ComponentsCommand.self, ImportCommand.self, MCPCommand.self, BundleCommand.self, - MarketplaceCommand.self, PolicyCommand.self, + MarketplaceCommand.self, PolicyCommand.self, AuditCommand.self, ] ) 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) + } +} From fca5a17f8efcad53aedf6af6c1053b991debeb2d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 22:58:47 +0800 Subject: [PATCH 39/67] feat: manage marketplace dependency graphs from the CLI --- Documentation/Reference/CLI.md | 82 +++++- .../Schemas/marketplace-preview.schema.json | 25 ++ .../marketplace-resolution.schema.json | 86 ++++++ Sources/CLI/BundleCommands.swift | 21 +- Sources/CLI/MarketplaceCommands.swift | 184 +++++++++++-- Sources/CLI/MarketplaceGraphCommands.swift | 228 ++++++++++++++++ Sources/CLI/MarketplaceReports.swift | 248 +++++++++++++++++ .../CLITests/MarketplaceExecutableTests.swift | 258 ++++++++++++++++++ 8 files changed, 1099 insertions(+), 33 deletions(-) create mode 100644 Documentation/Reference/Schemas/marketplace-preview.schema.json create mode 100644 Documentation/Reference/Schemas/marketplace-resolution.schema.json create mode 100644 Sources/CLI/MarketplaceGraphCommands.swift create mode 100644 Sources/CLI/MarketplaceReports.swift create mode 100644 Tests/CLITests/MarketplaceExecutableTests.swift diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 7872107..005112b 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -32,19 +32,22 @@ agents components list [ --group --alias ] [--json] [--sc 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 export --name --package-version --component … [--scope ] +agents bundle export --name --package-version --component … [--dependency ]… [--scope ] agents bundle inspect agents bundle import --agent … [--component ] [--scope ] [--json | --apply] -agents marketplace publish (--directory | --catalog ) [--summary ] +agents marketplace publish (--directory | --catalog ) [--summary ] [--scope ] agents marketplace register (--directory | --git [--ref ] [--subpath ]) [--scope ] agents marketplace list [--scope ] agents marketplace unregister [--scope ] -agents marketplace search [] (--catalog | --directory | --git [--ref ] [--subpath ]) -agents marketplace install (--catalog | --directory | --git ) --agent … [--package-version ] [--alias ] [--json | --apply] +agents marketplace search [] [--scope ] +agents marketplace resolve [ [] [--alias ]] [--json] [--scope ] +agents marketplace install (--agent … [--component … | --member …] | --metadata-only) [] [--alias ] [--replace] [--binding NAME=ENV_VAR] [--json | --apply] [--scope ] agents marketplace installed [--scope ] +agents marketplace deps [--scope ] +agents marketplace why [--scope ] agents marketplace outdated [] [--scope ] -agents marketplace upgrade [--package-version ] [--scope ] [--apply] [--json] -agents marketplace remove [--scope ] [--json | --apply] +agents marketplace upgrade [] [--agent … --member …] [--binding NAME=ENV_VAR] [--scope ] [--json | --apply] +agents marketplace remove [--binding NAME=ENV_VAR] [--scope ] [--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] @@ -359,6 +362,70 @@ 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. +## Bundles and Marketplaces + +Register a catalog with `marketplace register --directory ` or +`--git `. Catalog options for browsing, resolving and installing +are `--catalog `, `--directory `, or `--git ` with +optional `--ref` and `--subpath`. 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. + +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 embeds a registered portable Git catalog's origin. +`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 `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 public registry, then `mcp show` to inspect an exact version, @@ -852,6 +919,9 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | `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` | +| `marketplace resolve --json` | [Marketplace resolution](Schemas/marketplace-resolution.schema.json) | `schemaVersion`, `scope`, `roots`, `nodes` | +| `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: 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..5441920 --- /dev/null +++ b/Documentation/Reference/Schemas/marketplace-resolution.schema.json @@ -0,0 +1,86 @@ +{ + "$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"] }, + "catalogOrigin": { "type": "string" }, + "subpath": { "type": "string" } + }, + "required": ["package", "catalogKind", "catalogOrigin"] + }, + "catalog": { + "type": "object", + "properties": { + "kind": { "enum": ["directory", "git"] }, + "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/Sources/CLI/BundleCommands.swift b/Sources/CLI/BundleCommands.swift index 14ece77..c76f72f 100644 --- a/Sources/CLI/BundleCommands.swift +++ b/Sources/CLI/BundleCommands.swift @@ -17,6 +17,8 @@ struct ExportBundle: ParsableCommand { @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 { @@ -29,8 +31,19 @@ struct ExportBundle: ParsableCommand { } 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), selections: selected, + BundlePackage(name: name, version: packageVersion, dependencies: dependencies), + selections: selected, scope: location.scope, environment: RuntimeEnvironment()) try data.write(to: URL(fileURLWithPath: output), options: .withoutOverwriting) } @@ -45,6 +58,12 @@ struct InspectBundle: ParsableCommand { 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" diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift index 4220dae..1a2dea5 100644 --- a/Sources/CLI/MarketplaceCommands.swift +++ b/Sources/CLI/MarketplaceCommands.swift @@ -10,7 +10,8 @@ struct MarketplaceCommand: ParsableCommand { RegisterMarketplace.self, ListMarketplaces.self, UnregisterMarketplace.self, SearchMarketplace.self, PublishPackage.self, InstallMarketPackage.self, InstalledPackages.self, OutdatedPackages.self, UpgradeMarketPackage.self, - RemoveMarketPackage.self, + RemoveMarketPackage.self, ResolveMarketPackages.self, MarketplaceDependencies.self, + MarketplaceWhy.self, ]) } @@ -51,6 +52,10 @@ struct CatalogOptions: ParsableArguments { return try MarketplaceRegistration(name: "catalog", origin: directOrigin(anchorDirectory: true)) } + var specified: Bool { + catalog != nil || directory != nil || git != nil || ref != nil || subpath != nil + } + func browse(in scope: InstallScope) throws -> MarketplaceCatalog { try MarketplaceOperations.browse(registration(in: scope), scope: scope) } @@ -138,14 +143,25 @@ struct InstalledPackages: ParsableCommand { @OptionGroup var location: ScopeOptions func run() throws { - let pins = try MarketplaceOperations.installed(scope: location.scope) + 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 pins.isEmpty { Terminal.write("No marketplace packages installed.\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") } } } @@ -156,17 +172,27 @@ struct OutdatedPackages: ParsableCommand { @Argument(help: "Installed dependency name. Omit to check all packages.") var name: String? func run() throws { - let installed = try MarketplaceOperations.installed(scope: location.scope) - let pins = installed.filter { name == nil || name == $0.dependency.name } - if let name, pins.isEmpty { throw MarketplaceError.missingPin(name) } + 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: location.scope) + 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" ) } - if pins.isEmpty { Terminal.write("No marketplace packages installed.\n") } + for root in roots { + let alias = root.intent.name + let report = try MarketplaceOperations.resolve(.upgrade(alias), scope: scope) + 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") } } } @@ -175,15 +201,26 @@ struct UpgradeMarketPackage: ParsableCommand { commandName: "upgrade", abstract: "Review a newer release using this project's installed selections.") @Argument(help: "Installed dependency name.") var name: String - @Option(help: "Newer release to select. Defaults to the newest available version.") - var packageVersion: String? + @OptionGroup var version: MarketplaceVersionOptions + @OptionGroup var members: MarketplaceMemberOptions @OptionGroup var options: UpdateOptions @OptionGroup var bindings: BindingOptions func run() throws { let scope = options.location.scope - let inspection = try UpdateOperations.inspect(scope: scope) - try requireCommittedInspection(inspection) + 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 inspection.marketplaceGraph?.roots.contains(where: { $0.intent.name == name }) == true + || version.requirementExpression != nil || !members.member.isEmpty + { + try options.finishMarketplace( + .upgrade(name, requirement: requirement, selections: try members.selections(in: scope)), + bindings: bindings) + return + } guard let pin = inspection.marketplacePackages.first(where: { $0.dependency.name == name }) else { throw MarketplaceError.missingPin(name) @@ -191,10 +228,12 @@ struct UpgradeMarketPackage: ParsableCommand { let newer = try MarketplaceOperations.availableUpdates(for: pin, scope: scope) guard let release = newer.first(where: { - packageVersion == nil || $0.coordinate.version == packageVersion + version.packageVersion == nil || $0.coordinate.version == version.packageVersion }) else { - if let packageVersion { throw MarketplaceError.releaseNotFound(name + "@" + packageVersion) } + if let packageVersion = version.packageVersion { + throw MarketplaceError.releaseNotFound(name + "@" + packageVersion) + } if options.json { try Terminal.json(UpdateReport(scope: scope.rawValue, results: [])) } else { @@ -203,7 +242,13 @@ struct UpgradeMarketPackage: ParsableCommand { return } let verified = try MarketplaceOperations.acquire(release, scope: scope) - let selections = try verified.inspectBundle().retainedSelections(for: pin, in: inspection) + let bundle = try verified.inspectBundle() + if bundle.package.dependencies != nil { + try options.finishMarketplace( + .upgrade(name, requirement: .exact(release.coordinate.version)), bindings: bindings) + 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." @@ -218,21 +263,103 @@ struct InstallMarketPackage: ParsableCommand { 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 - @Option(help: "Exact release. Omit to select the latest version.") var packageVersion: String? + @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 installation: BundleInstallOptions + @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 + @OptionGroup var options: UpdateOptions + @OptionGroup var bindings: BindingOptions + + func validate() throws { + 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() throws { - let scope = installation.options.location.scope - let release = try source.browse(in: scope).select(package: package, version: packageVersion) - let verified = try MarketplaceOperations.acquire(release, scope: scope) - let contents = try verified.inspectBundle() - let preview = try verified.previewImport( - as: alias ?? package, selections: installation.selections(in: contents), - scope: installation.options.location.scope, replace: installation.replace) - try installation.finish(preview) + let scope = options.location.scope + let name = alias ?? package + let registration = try source.registration(in: scope) + 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 = + existing == nil && version.requirementExpression == nil && !metadataOnly + && 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).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) + } + let preview = try verified.previewImport( + as: name, selections: selections, scope: scope, replace: replace) + try options.finishImport(preview, bindings: bindings) + 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 options.finishMarketplace(.install(root([])), bindings: bindings, replace: replace) + } else if let selected = try members.selections(in: scope) { + try options.finishMarketplace(.install(root(selected)), bindings: bindings, replace: replace) + } else { + let candidate = try MarketplaceOperations.resolve(.install(root([])), scope: scope) + 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 options.finishMarketplace( + .install(root(selections)), bindings: bindings, replace: replace + ) { resolution in + guard resolution.rootMembers(named: name)?.map(\.id) == available.map(\.id) else { + throw ValidationError("Available package members changed; run marketplace install again") + } + } + } } } @@ -244,8 +371,13 @@ struct RemoveMarketPackage: ParsableCommand { @OptionGroup var bindings: BindingOptions func run() throws { - let request = MarketplaceOperations.removalRequest(for: name) let scope = options.location.scope + let inspection = try committedMarketplaceInspection(scope) + if inspection.marketplaceGraph?.roots.contains(where: { $0.intent.name == name }) == true { + try options.finishMarketplace(.remove(name), bindings: bindings) + return + } + let request = MarketplaceOperations.removalRequest(for: name) let report = try UpdateOperations.preview(request, scope: scope) if options.json { try Terminal.json(UpdateReport(report)) diff --git a/Sources/CLI/MarketplaceGraphCommands.swift b/Sources/CLI/MarketplaceGraphCommands.swift new file mode 100644 index 0000000..d897f7b --- /dev/null +++ b/Sources/CLI/MarketplaceGraphCommands.swift @@ -0,0 +1,228 @@ +import AgentsCore +import AgentsUpdates +import ArgumentParser +import Foundation + +struct MarketplaceVersionOptions: ParsableArguments { + @Option(help: "Exact package release.") var packageVersion: String? + @Option( + name: .customLong("requirement"), + help: "Version constraint: 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 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 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).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) + 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 UpdateOptions { + func finishMarketplace( + _ request: MarketplaceResolutionRequest, bindings: BindingOptions, replace: Bool = false, + checking check: (MarketplaceResolution) throws -> Void = { _ in } + ) throws { + let preview = try MarketplaceOperations.previewResolution( + request, scope: location.scope, replace: replace) + 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 apply { + _ = try MarketplaceOperations.withPreparedResolution( + preview, bindingProvider: bindings.provider() + ) { + try $0.apply(ifUnchangedFrom: preview.report.displayedFingerprint) + } + } 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..35ce108 --- /dev/null +++ b/Sources/CLI/MarketplaceReports.swift @@ -0,0 +1,248 @@ +import AgentsCore +import AgentsUpdates + +struct MarketplaceResolutionReport: Encodable { + struct NodeID: Encodable { + let package: String + let catalogKind: String + let catalogOrigin: String + let subpath: String? + + init(_ id: MarketplaceNodeID) { + package = id.package + catalogKind = id.catalog.kind.rawValue + catalogOrigin = id.catalog.origin.description + 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/Tests/CLITests/MarketplaceExecutableTests.swift b/Tests/CLITests/MarketplaceExecutableTests.swift new file mode 100644 index 0000000..9fa907f --- /dev/null +++ b/Tests/CLITests/MarketplaceExecutableTests.swift @@ -0,0 +1,258 @@ +import Foundation +import Testing + +struct MarketplaceExecutableTests { + @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)) + } + + 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 + } +} From ad0bc4eaebff051df07e25de73bbe5cde84360e7 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:09:16 +0800 Subject: [PATCH 40/67] fix: clarify marketplace command messages --- Sources/CLI/MarketplaceCommands.swift | 2 +- Sources/CLI/MarketplaceGraphCommands.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift index 1a2dea5..a29a52c 100644 --- a/Sources/CLI/MarketplaceCommands.swift +++ b/Sources/CLI/MarketplaceCommands.swift @@ -356,7 +356,7 @@ struct InstallMarketPackage: ParsableCommand { .install(root(selections)), bindings: bindings, replace: replace ) { resolution in guard resolution.rootMembers(named: name)?.map(\.id) == available.map(\.id) else { - throw ValidationError("Available package members changed; run marketplace install again") + throw ValidationError("Available package members changed. Run marketplace install again") } } } diff --git a/Sources/CLI/MarketplaceGraphCommands.swift b/Sources/CLI/MarketplaceGraphCommands.swift index d897f7b..079691f 100644 --- a/Sources/CLI/MarketplaceGraphCommands.swift +++ b/Sources/CLI/MarketplaceGraphCommands.swift @@ -7,7 +7,7 @@ struct MarketplaceVersionOptions: ParsableArguments { @Option(help: "Exact package release.") var packageVersion: String? @Option( name: .customLong("requirement"), - help: "Version constraint: VERSION, major:VERSION, minor:VERSION, or LOWER.. SourceRequirement? { From 1a2b64092230f6fb2eed85bfcd0b90b0c0752a51 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:54:16 +0800 Subject: [PATCH 41/67] feat: report scoped organization policy in status and CI --- Documentation/Reference/CLI.md | 6 ++- Documentation/Reference/ManifestDump.md | 2 +- .../Reference/Schemas/doctor.schema.json | 1 + Package.resolved | 4 +- Package.swift | 2 +- README.md | 2 +- Sources/CLI/LifecycleCommands.swift | 43 ++++++++++++++----- Sources/CLI/PolicyCommand.swift | 40 ++++++++++++++++- Tests/CLITests/ComponentExecutableTests.swift | 5 ++- 9 files changed, 85 insertions(+), 20 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index ef6babe..3071799 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -760,7 +760,7 @@ 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 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 the policy identified by `AGENTS_ORGANIZATION_SOURCE_POLICY`. The audit checks locked sources against each applicable source policy. A violation or an unreadable policy produces an error and exit status 1. +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 @@ -772,7 +772,7 @@ current directory and user scope uses HOME. | 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/2956f97660315b534c4dd32dbb122d2979ceb9ec/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/81b44d7312108ad57a578e2e8fcf3c7dcf9fc899/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 @@ -1056,6 +1056,8 @@ 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 diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 1daf06c..82a5b50 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/2956f97660315b534c4dd32dbb122d2979ceb9ec/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/81b44d7312108ad57a578e2e8fcf3c7dcf9fc899/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. diff --git a/Documentation/Reference/Schemas/doctor.schema.json b/Documentation/Reference/Schemas/doctor.schema.json index 1a2d585..a415633 100644 --- a/Documentation/Reference/Schemas/doctor.schema.json +++ b/Documentation/Reference/Schemas/doctor.schema.json @@ -54,6 +54,7 @@ "instructions", "components", "sourcePolicy", + "organizationPolicy", "marketplace" ] } diff --git a/Package.resolved b/Package.resolved index 8dd1f9c..3b927fc 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "5562df8e250e481fa5d3d2b63a22e9ea3fd2f6222dd6f2893b65e30ad9270c4a", + "originHash" : "3faacae1b15528b042067a9acd2b59ced32f3d9afbbb041b6dedbbaac2fe5e06", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "2956f97660315b534c4dd32dbb122d2979ceb9ec" + "revision" : "81b44d7312108ad57a578e2e8fcf3c7dcf9fc899" } }, { diff --git a/Package.swift b/Package.swift index b922fbf..4aad4db 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "2956f97660315b534c4dd32dbb122d2979ceb9ec"), + revision: "81b44d7312108ad57a578e2e8fcf3c7dcf9fc899"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index d6cab92..fde2695 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/2956f97660315b534c4dd32dbb122d2979ceb9ec/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/81b44d7312108ad57a578e2e8fcf3c7dcf9fc899/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. diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index aeed091..310e792 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -205,16 +205,39 @@ struct Doctor: ParsableCommand { policyChecks = [] } else { do { - let audit = try SourcePolicyOperations.audit(scope: location.scope, environment: runtime) - var checks = audit.violations.map(CheckItem.init) - if requireOrganizationPolicy - && !audit.policy.effective.layers.contains(where: { $0.scope == .organization }) - { - checks.append( - CheckItem( - kind: "sourcePolicy", id: "missingOrganizationPolicy", status: "error", - message: "Set AGENTS_ORGANIZATION_SOURCE_POLICY to the organization policy file.", - path: nil)) + 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 } + checks = + audit.sourceViolations.map(CheckItem.init) + + audit.organization.findings.map { finding in + CheckItem( + 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 }) + } + } 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 { diff --git a/Sources/CLI/PolicyCommand.swift b/Sources/CLI/PolicyCommand.swift index a051ef7..2f4deab 100644 --- a/Sources/CLI/PolicyCommand.swift +++ b/Sources/CLI/PolicyCommand.swift @@ -6,8 +6,10 @@ import Foundation struct PolicyCommand: ParsableCommand { static let configuration = CommandConfiguration( - commandName: "policy", abstract: "Inspect and configure allowed sources.", - subcommands: [ShowSourcePolicy.self, SetSourcePolicy.self]) + commandName: "policy", abstract: "Inspect organization policy and configure allowed sources.", + subcommands: [ + ShowSourcePolicy.self, SetSourcePolicy.self, OrganizationPolicyStatusCommand.self, + ]) } struct ShowSourcePolicy: ParsableCommand { @@ -54,3 +56,37 @@ struct SetSourcePolicy: ParsableCommand { } } } + +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 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/Tests/CLITests/ComponentExecutableTests.swift b/Tests/CLITests/ComponentExecutableTests.swift index a66bba2..87c0beb 100644 --- a/Tests/CLITests/ComponentExecutableTests.swift +++ b/Tests/CLITests/ComponentExecutableTests.swift @@ -79,7 +79,10 @@ struct ComponentExecutableTests { let inventory = try fixture.success(["components", "inventory"]) let packages = try #require(try inventory.json()["components"] as? [[String: Any]]) let package = try #require( - packages.first { $0["name"] as? String == fixture.source.lastPathComponent }) + 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") From 340a2d1ea39322690c3f0d61a3bd8918e790c676 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 00:08:16 +0800 Subject: [PATCH 42/67] feat: verify team marketplace releases from the CLI --- Documentation/Reference/CLI.md | 3 ++- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- Sources/CLI/MarketplaceCommands.swift | 21 ++++++++++++++++++++- 6 files changed, 27 insertions(+), 7 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 3071799..ed91863 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -40,6 +40,7 @@ agents marketplace register (--directory | --git 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] [--json | --apply] [--scope ] agents marketplace installed [--scope ] @@ -772,7 +773,7 @@ current directory and user scope uses HOME. | 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/81b44d7312108ad57a578e2e8fcf3c7dcf9fc899/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/b47aae8448118b6da37a289368231f8f825457ac/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 82a5b50..5e05e20 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/81b44d7312108ad57a578e2e8fcf3c7dcf9fc899/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/b47aae8448118b6da37a289368231f8f825457ac/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. diff --git a/Package.resolved b/Package.resolved index 3b927fc..d708da4 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "3faacae1b15528b042067a9acd2b59ced32f3d9afbbb041b6dedbbaac2fe5e06", + "originHash" : "6f39eb4529ca9f74f520771de38328471237ed8f5fb2b83da8920cb19c68e19f", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "81b44d7312108ad57a578e2e8fcf3c7dcf9fc899" + "revision" : "b47aae8448118b6da37a289368231f8f825457ac" } }, { diff --git a/Package.swift b/Package.swift index 4aad4db..632708f 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "81b44d7312108ad57a578e2e8fcf3c7dcf9fc899"), + revision: "b47aae8448118b6da37a289368231f8f825457ac"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index fde2695..2d41e9a 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/81b44d7312108ad57a578e2e8fcf3c7dcf9fc899/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/b47aae8448118b6da37a289368231f8f825457ac/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. diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift index a29a52c..691cb46 100644 --- a/Sources/CLI/MarketplaceCommands.swift +++ b/Sources/CLI/MarketplaceCommands.swift @@ -8,7 +8,8 @@ struct MarketplaceCommand: ParsableCommand { commandName: "marketplace", abstract: "Browse team packages and manage their releases.", subcommands: [ RegisterMarketplace.self, ListMarketplaces.self, UnregisterMarketplace.self, - SearchMarketplace.self, PublishPackage.self, InstallMarketPackage.self, + SearchMarketplace.self, VerifyMarketplace.self, PublishPackage.self, + InstallMarketPackage.self, InstalledPackages.self, OutdatedPackages.self, UpgradeMarketPackage.self, RemoveMarketPackage.self, ResolveMarketPackages.self, MarketplaceDependencies.self, MarketplaceWhy.self, @@ -115,6 +116,24 @@ struct SearchMarketplace: ParsableCommand { } } +struct VerifyMarketplace: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "verify", abstract: "Verify the metadata and bundle of every marketplace release.") + @OptionGroup var location: ScopeOptions + @OptionGroup var source: CatalogOptions + + func run() throws { + let catalog = try MarketplaceOperations.verifyCatalog( + source.registration(in: location.scope), scope: location.scope) + 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.") From 2da1597923fd9b76de51820951aed304a3446a21 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:31:27 +0800 Subject: [PATCH 43/67] feat: publish authored packages and deploy locked marketplace selections --- Documentation/Reference/CLI.md | 44 +++-- Documentation/Reference/ManifestDump.md | 2 +- .../Schemas/marketplace-pending.schema.json | 33 ++++ .../marketplace-resolution.schema.json | 9 +- Package.resolved | 4 +- Package.swift | 2 +- README.md | 2 +- Sources/CLI/AuthorPackageCommands.swift | 109 +++++++++++++ Sources/CLI/BundleCommands.swift | 3 +- Sources/CLI/JSONReports.swift | 16 +- Sources/CLI/LifecycleCommands.swift | 12 +- Sources/CLI/MarketplaceCommands.swift | 154 +++++++++++++++--- Sources/CLI/MarketplaceDeployment.swift | 79 +++++++++ Sources/CLI/MarketplaceGraphCommands.swift | 15 +- Sources/CLI/MarketplaceReports.swift | 2 + Sources/CLI/PolicyCommand.swift | 7 + .../CLITests/MarketplaceExecutableTests.swift | 90 ++++++++++ 17 files changed, 529 insertions(+), 54 deletions(-) create mode 100644 Documentation/Reference/Schemas/marketplace-pending.schema.json create mode 100644 Sources/CLI/AuthorPackageCommands.swift create mode 100644 Sources/CLI/MarketplaceDeployment.swift diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index ed91863..ad332bb 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -32,23 +32,29 @@ agents components list [ --group --alias ] [--json] [--sc 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 ] [--output ] [--reviewed-digest ] agents bundle export --name --package-version --component … [--dependency ]… [--scope ] agents bundle inspect agents bundle import --agent … [--component ] [--scope ] [--json | --apply] agents marketplace publish (--directory | --catalog ) [--summary ] [--scope ] -agents marketplace register (--directory | --git [--ref ] [--subpath ]) [--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] [--json | --apply] [--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 ] [--json | --apply] -agents marketplace remove [--binding NAME=ENV_VAR] [--scope ] [--json | --apply] +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] @@ -367,18 +373,30 @@ usage error. ## Bundles and Marketplaces -Register a catalog with `marketplace register --directory ` or -`--git `. Catalog options for browsing, resolving and installing -are `--catalog `, `--directory `, or `--git ` with -optional `--ref` and `--subpath`. Project registrations take precedence over +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. + 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 embeds a registered portable Git catalog's origin. +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 @@ -394,6 +412,10 @@ you explicitly replace them. Use `--requirement` to change the constraint or 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 @@ -773,7 +795,7 @@ current directory and user scope uses HOME. | 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/b47aae8448118b6da37a289368231f8f825457ac/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a/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 @@ -968,6 +990,8 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | `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` | | `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` | diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 5e05e20..1e0845a 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/b47aae8448118b6da37a289368231f8f825457ac/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a/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. 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-resolution.schema.json b/Documentation/Reference/Schemas/marketplace-resolution.schema.json index 5441920..b424789 100644 --- a/Documentation/Reference/Schemas/marketplace-resolution.schema.json +++ b/Documentation/Reference/Schemas/marketplace-resolution.schema.json @@ -14,16 +14,19 @@ "type": "object", "properties": { "package": { "type": "string" }, - "catalogKind": { "enum": ["directory", "git"] }, + "catalogKind": { "enum": ["directory", "git", "hosted"] }, "catalogOrigin": { "type": "string" }, + "hostedIndex": { "type": "string", "format": "uri", "pattern": "^https://" }, "subpath": { "type": "string" } }, - "required": ["package", "catalogKind", "catalogOrigin"] + "required": ["package", "catalogKind", "catalogOrigin"], + "if": { "properties": { "catalogKind": { "const": "hosted" } } }, + "then": { "required": ["hostedIndex"] } }, "catalog": { "type": "object", "properties": { - "kind": { "enum": ["directory", "git"] }, + "kind": { "enum": ["directory", "git", "hosted"] }, "location": { "type": "string" }, "ref": { "type": "string" }, "subpath": { "type": "string" } diff --git a/Package.resolved b/Package.resolved index d708da4..4654730 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "6f39eb4529ca9f74f520771de38328471237ed8f5fb2b83da8920cb19c68e19f", + "originHash" : "9ed89e6f221a876b7b0d17a5406c0e02e4b1037d85108d6fc4db703a388a86f1", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "b47aae8448118b6da37a289368231f8f825457ac" + "revision" : "b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a" } }, { diff --git a/Package.swift b/Package.swift index 632708f..2f108cc 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "b47aae8448118b6da37a289368231f8f825457ac"), + revision: "b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 2d41e9a..234dba4 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/b47aae8448118b6da37a289368231f8f825457ac/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a/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. diff --git a/Sources/CLI/AuthorPackageCommands.swift b/Sources/CLI/AuthorPackageCommands.swift new file mode 100644 index 0000000..fd1f170 --- /dev/null +++ b/Sources/CLI/AuthorPackageCommands.swift @@ -0,0 +1,109 @@ +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: "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: ", ")) + } + let plugin = try NativePluginOperations.preview( + AuthorPackageOperations.preview(), for: target, + marketplace: marketplace.map { NativePluginMarketplace(name: $0) }) + 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/BundleCommands.swift b/Sources/CLI/BundleCommands.swift index c76f72f..83802fb 100644 --- a/Sources/CLI/BundleCommands.swift +++ b/Sources/CLI/BundleCommands.swift @@ -6,7 +6,8 @@ import Foundation struct BundleCommand: ParsableCommand { static let configuration = CommandConfiguration( commandName: "bundle", abstract: "Share selected instructions, skills and MCP servers.", - subcommands: [ExportBundle.self, InspectBundle.self, ImportBundle.self]) + subcommands: [CreateAuthorProject.self, PackAuthorProject.self, ExportNativePlugin.self, + ExportBundle.self, InspectBundle.self, ImportBundle.self]) } struct ExportBundle: ParsableCommand { diff --git a/Sources/CLI/JSONReports.swift b/Sources/CLI/JSONReports.swift index 881068d..65ad5c6 100644 --- a/Sources/CLI/JSONReports.swift +++ b/Sources/CLI/JSONReports.swift @@ -326,6 +326,14 @@ struct CheckItem: Encodable { 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 @@ -357,7 +365,13 @@ struct CheckItem: Encodable { [.init(kind: "marketplace", id: "package-lock", status: "error", message: $0.description, path: StateStore(scope: inspection.scope, environment: environment).declarationURL.path)] } ?? [] - return packageChecks + inspection.deployments.filter { !owners.isDisjoint(with: $0.ownerRecords) }.map { + 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)", diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index 310e792..5e02bac 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -214,15 +214,13 @@ struct Doctor: ParsableCommand { 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) - + audit.organization.findings.map { finding in - CheckItem( - 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 }) - } + + findings.map(CheckItem.init) } else { let audit = try SourcePolicyOperations.audit( scope: location.scope, environment: runtime) diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift index 691cb46..d7943f4 100644 --- a/Sources/CLI/MarketplaceCommands.swift +++ b/Sources/CLI/MarketplaceCommands.swift @@ -9,15 +9,17 @@ struct MarketplaceCommand: ParsableCommand { 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, + 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? @@ -26,26 +28,29 @@ struct CatalogOptions: ParsableArguments { func directOrigin(anchorDirectory: Bool = false) throws -> MarketplaceOrigin { guard catalog == nil else { - throw ValidationError("Choose a directory or Git repository to register") + throw ValidationError("Choose a directory, Git repository or hosted index to register") } let origin: MarketplaceOrigin - switch (directory, git) { - case (let path?, nil) where ref == nil && subpath == nil: + 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?): + 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( - "Specify either --directory or --git; --ref and --subpath require --git") + "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, ref == nil, subpath == nil else { + 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) @@ -54,11 +59,47 @@ struct CatalogOptions: ParsableArguments { } var specified: Bool { - catalog != nil || directory != nil || git != nil || ref != nil || subpath != nil + catalog != nil || directory != nil || git != nil || index != nil || ref != nil || subpath != nil } - func browse(in scope: InstallScope) throws -> MarketplaceCatalog { - try MarketplaceOperations.browse(registration(in: scope), scope: scope) +} + +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] } } } @@ -101,12 +142,15 @@ struct UnregisterMarketplace: ParsableCommand { 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 releases = try source.browse(in: location.scope).search(query ?? "") + 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" @@ -119,12 +163,13 @@ struct SearchMarketplace: ParsableCommand { 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) + 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" @@ -156,6 +201,21 @@ struct PublishPackage: ParsableCommand { } } +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.") @@ -181,12 +241,25 @@ struct InstalledPackages: ParsableCommand { } } 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? @@ -207,7 +280,8 @@ struct OutdatedPackages: ParsableCommand { } for root in roots { let alias = root.intent.name - let report = try MarketplaceOperations.resolve(.upgrade(alias), scope: scope) + 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]) } @@ -220,8 +294,11 @@ struct UpgradeMarketPackage: ParsableCommand { 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 @@ -232,12 +309,13 @@ struct UpgradeMarketPackage: ParsableCommand { guard members.agent.isEmpty || !members.member.isEmpty else { throw ValidationError("--agent on upgrade requires --member") } - if inspection.marketplaceGraph?.roots.contains(where: { $0.intent.name == name }) == true + if lockOnly + || inspection.marketplaceGraph?.roots.contains(where: { $0.intent.name == name }) == true || version.requirementExpression != nil || !members.member.isEmpty { try options.finishMarketplace( .upgrade(name, requirement: requirement, selections: try members.selections(in: scope)), - bindings: bindings) + bindings: bindings, lockOnly: lockOnly, hostedAccess: hosted.access()) return } guard let pin = inspection.marketplacePackages.first(where: { $0.dependency.name == name }) @@ -264,7 +342,8 @@ struct UpgradeMarketPackage: ParsableCommand { let bundle = try verified.inspectBundle() if bundle.package.dependencies != nil { try options.finishMarketplace( - .upgrade(name, requirement: .exact(release.coordinate.version)), bindings: bindings) + .upgrade(name, requirement: .exact(release.coordinate.version)), bindings: bindings, + hostedAccess: hosted.access()) return } let selections = try bundle.retainedSelections(for: pin, in: inspection) @@ -282,6 +361,7 @@ struct InstallMarketPackage: ParsableCommand { 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? @@ -291,10 +371,13 @@ struct InstallMarketPackage: ParsableCommand { 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") @@ -312,20 +395,24 @@ struct InstallMarketPackage: ParsableCommand { 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 = - existing == nil && version.requirementExpression == nil && !metadataOnly + 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).select( + 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) @@ -350,11 +437,23 @@ struct InstallMarketPackage: ParsableCommand { selections: selections) } if metadataOnly { - try options.finishMarketplace(.install(root([])), bindings: bindings, replace: replace) + try options.finishMarketplace( + .install(root([])), bindings: bindings, replace: replace, lockOnly: lockOnly, + hostedAccess: access) } else if let selected = try members.selections(in: scope) { - try options.finishMarketplace(.install(root(selected)), bindings: bindings, replace: replace) + try options.finishMarketplace( + .install(root(selected)), bindings: bindings, replace: replace, lockOnly: lockOnly, + hostedAccess: access) } else { - let candidate = try MarketplaceOperations.resolve(.install(root([])), scope: scope) + 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") } @@ -372,7 +471,8 @@ struct InstallMarketPackage: ParsableCommand { package: package, member: $0.marketplaceKey, targets: members.agent) } try options.finishMarketplace( - .install(root(selections)), bindings: bindings, replace: replace + .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") @@ -386,14 +486,20 @@ struct RemoveMarketPackage: ParsableCommand { 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() throws { let scope = options.location.scope let inspection = try committedMarketplaceInspection(scope) - if inspection.marketplaceGraph?.roots.contains(where: { $0.intent.name == name }) == true { - try options.finishMarketplace(.remove(name), bindings: bindings) + if lockOnly + || inspection.marketplaceGraph?.roots.contains(where: { $0.intent.name == name }) == true + { + try options.finishMarketplace( + .remove(name), bindings: bindings, lockOnly: lockOnly, hostedAccess: hosted.access()) return } let request = MarketplaceOperations.removalRequest(for: name) diff --git a/Sources/CLI/MarketplaceDeployment.swift b/Sources/CLI/MarketplaceDeployment.swift new file mode 100644 index 0000000..cb9c04f --- /dev/null +++ b/Sources/CLI/MarketplaceDeployment.swift @@ -0,0 +1,79 @@ +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: ParsableCommand { + 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() throws { try options.finishPendingLock(.reconcile, hostedAccess: hosted.access()) } +} + +extension UpdateOptions { + func finishPendingLock( + _ request: MarketplaceResolutionRequest, hostedAccess: HostedMarketplaceAccess? = nil, + checking check: (MarketplaceResolution) throws -> Void = { _ in } + ) throws { + let preview = try 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 apply { + _ = try MarketplaceOperations.writeLockOnly(preview) + } else if !json { + previewNotice(changed: preview.report.hasChanges) + } + } +} + +struct DeployLockedMarketPackages: ParsableCommand { + 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() throws { + let preview = try MarketplaceOperations.previewFrozenDeployment( + scope: options.location.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.apply { + _ = try MarketplaceOperations.deployFrozen(preview, bindingProvider: bindings.provider()) + } else if !options.json { + options.previewNotice(changed: preview.report.hasChanges) + } + } +} diff --git a/Sources/CLI/MarketplaceGraphCommands.swift b/Sources/CLI/MarketplaceGraphCommands.swift index 079691f..dc7c38c 100644 --- a/Sources/CLI/MarketplaceGraphCommands.swift +++ b/Sources/CLI/MarketplaceGraphCommands.swift @@ -84,6 +84,7 @@ struct ResolveMarketPackages: ParsableCommand { @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 @@ -92,6 +93,7 @@ struct ResolveMarketPackages: ParsableCommand { 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) @@ -99,7 +101,9 @@ struct ResolveMarketPackages: ParsableCommand { if let requirement { constraint = requirement } else { - let release = try MarketplaceOperations.browse(registration, scope: scope).select( + let release = try MarketplaceOperations.browse( + registration, scope: scope, hostedAccess: access + ).select( package: package) constraint = .exact(release.coordinate.version) } @@ -113,7 +117,7 @@ struct ResolveMarketPackages: ParsableCommand { } request = .reconcile } - let result = try MarketplaceOperations.resolve(request, scope: scope) + let result = try MarketplaceOperations.resolve(request, scope: scope, hostedAccess: access) if json { try Terminal.json(MarketplaceResolutionReport(result, scope: scope)) } else { @@ -200,10 +204,15 @@ extension MarketplaceResolution { extension UpdateOptions { func finishMarketplace( _ request: MarketplaceResolutionRequest, bindings: BindingOptions, replace: Bool = false, + lockOnly: Bool = false, hostedAccess: HostedMarketplaceAccess? = nil, checking check: (MarketplaceResolution) throws -> Void = { _ in } ) throws { + if lockOnly { + try finishPendingLock(request, hostedAccess: hostedAccess, checking: check) + return + } let preview = try MarketplaceOperations.previewResolution( - request, scope: location.scope, replace: replace) + request, scope: location.scope, replace: replace, hostedAccess: hostedAccess) try check(preview.resolution) if json { try Terminal.json(MarketplacePreviewReport(preview)) diff --git a/Sources/CLI/MarketplaceReports.swift b/Sources/CLI/MarketplaceReports.swift index 35ce108..1630408 100644 --- a/Sources/CLI/MarketplaceReports.swift +++ b/Sources/CLI/MarketplaceReports.swift @@ -6,12 +6,14 @@ struct MarketplaceResolutionReport: 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 } } diff --git a/Sources/CLI/PolicyCommand.swift b/Sources/CLI/PolicyCommand.swift index 2f4deab..5ae6375 100644 --- a/Sources/CLI/PolicyCommand.swift +++ b/Sources/CLI/PolicyCommand.swift @@ -82,6 +82,13 @@ struct OrganizationPolicyStatusCommand: ParsableCommand { "\(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") diff --git a/Tests/CLITests/MarketplaceExecutableTests.swift b/Tests/CLITests/MarketplaceExecutableTests.swift index 9fa907f..dd58679 100644 --- a/Tests/CLITests/MarketplaceExecutableTests.swift +++ b/Tests/CLITests/MarketplaceExecutableTests.swift @@ -186,6 +186,96 @@ struct MarketplaceExecutableTests { #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)) + } + private func nodePackage(_ node: [String: Any]) -> String? { (node["id"] as? [String: Any])?["package"] as? String } From c9261b9a34ac5c3261954e7f0fd4c96265dc91a3 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 01:43:42 +0800 Subject: [PATCH 44/67] feat: inspect, prune and clean acquisition caches --- Documentation/Reference/CLI.md | 19 ++ .../Reference/Schemas/cache.schema.json | 246 ++++++++++++++++++ Sources/CLI/CacheCommand.swift | 181 +++++++++++++ Sources/CLI/EntryPoint.swift | 2 +- Sources/CLI/Terminal.swift | 1 + Tests/CLITests/CacheExecutableTests.swift | 32 +++ 6 files changed, 480 insertions(+), 1 deletion(-) create mode 100644 Documentation/Reference/Schemas/cache.schema.json create mode 100644 Sources/CLI/CacheCommand.swift create mode 100644 Tests/CLITests/CacheExecutableTests.swift diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index ed91863..d9e2918 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -35,6 +35,9 @@ agents import --format [--root ] [--select --name --package-version --component … [--dependency ]… [--scope ] agents bundle inspect agents bundle import --agent … [--component ] [--scope ] [--json | --apply] +agents cache info [--json] +agents cache clean [--apply] [--json] +agents cache prune [--days ] [--apply] [--json] agents marketplace publish (--directory | --catalog ) [--summary ] [--scope ] agents marketplace register (--directory | --git [--ref ] [--subpath ]) [--scope ] agents marketplace list [--scope ] @@ -365,6 +368,21 @@ 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. +## 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 Register a catalog with `marketplace register --directory ` or @@ -967,6 +985,7 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | `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` | +| `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 --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 | 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/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/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index 7b1bbeb..f3652b4 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -29,7 +29,7 @@ struct Agents: ParsableCommand { subcommands: [ Skills.self, InstructionsCommand.self, Watch.self, Manifest.self, Install.self, Update.self, Doctor.self, ComponentsCommand.self, ImportCommand.self, MCPCommand.self, BundleCommand.self, - MarketplaceCommand.self, PolicyCommand.self, AuditCommand.self, + MarketplaceCommand.self, CacheCommand.self, PolicyCommand.self, AuditCommand.self, ] ) diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 7b3781e..13ff6b2 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -162,6 +162,7 @@ enum Terminal { } static func failureMessage(_ error: Error) -> String { + if let cache = error as? AcquisitionCacheError { return cache.localizedDescription } if let error = error as? UpdateApplyError { return updateFailureMessage(error.disposition, underlyingError: error.underlyingError) } 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) + } +} From 928fb85f36a1066d9e7b1b19cb914cbf9db443cb Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:17:33 +0800 Subject: [PATCH 45/67] feat: export local edits as producer patches --- Documentation/Reference/CLI.md | 8 ++++ Sources/CLI/EntryPoint.swift | 2 +- Sources/CLI/ExportPatchCommand.swift | 57 ++++++++++++++++++++++++++++ 3 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 Sources/CLI/ExportPatchCommand.swift diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index ad332bb..226840d 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -63,6 +63,7 @@ agents manifest dump --json [--scope project|user] 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] ``` @@ -393,6 +394,13 @@ from other private indexes. For archive redirects to a trusted CDN, pass 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. +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 diff --git a/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index 7b1bbeb..23c55ff 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -29,7 +29,7 @@ struct Agents: ParsableCommand { subcommands: [ Skills.self, InstructionsCommand.self, Watch.self, Manifest.self, Install.self, Update.self, Doctor.self, ComponentsCommand.self, ImportCommand.self, MCPCommand.self, BundleCommand.self, - MarketplaceCommand.self, PolicyCommand.self, AuditCommand.self, + MarketplaceCommand.self, PolicyCommand.self, AuditCommand.self, ExportPatchCommand.self, ] ) 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? + } +} From 43abe404c384d3747bbfed66b63e18bae92a94da Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:22:36 +0800 Subject: [PATCH 46/67] fix: use immutable producer diagnostics for packaged deployments --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index ad332bb..7d833ec 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -795,7 +795,7 @@ current directory and user scope uses HOME. | 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/b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/cee0507f915bf4516ccb75a05753773d0f5e1a07/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 1e0845a..fa44b33 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/cee0507f915bf4516ccb75a05753773d0f5e1a07/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. diff --git a/Package.resolved b/Package.resolved index 4654730..69fbc70 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "9ed89e6f221a876b7b0d17a5406c0e02e4b1037d85108d6fc4db703a388a86f1", + "originHash" : "804c85e701441c196334d29b0d0eef1d3d350fc5b6ad3ecac89ab6f9fd2cfe80", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a" + "revision" : "cee0507f915bf4516ccb75a05753773d0f5e1a07" } }, { diff --git a/Package.swift b/Package.swift index 2f108cc..1dbd7ce 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a"), + revision: "cee0507f915bf4516ccb75a05753773d0f5e1a07"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 234dba4..91669fd 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/b0049fa4eb56b2bb12c1e9d6ad54171731a51b6a/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/cee0507f915bf4516ccb75a05753773d0f5e1a07/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 2dcbeac5027dac9942fd39527c84ffca598bef9f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:44:14 +0800 Subject: [PATCH 47/67] fix: use shared-directory admission for native installs --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index e921fb4..ad43052 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -813,7 +813,7 @@ current directory and user scope uses HOME. | 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/5f1826d04c7f7befc2dfa372c760ab5596619a99/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/43acdd60e045a98853997436defe346804e9ff34/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 05a21a3..8956fdf 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/5f1826d04c7f7befc2dfa372c760ab5596619a99/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/43acdd60e045a98853997436defe346804e9ff34/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. diff --git a/Package.resolved b/Package.resolved index 66652c1..06f1101 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "e68c5152d6152714c444a67763cc4359f4f872c3e5a9b6992c3efa1507af6f1a", + "originHash" : "4b10a46cc725a3a12aefebc303a536f89f515eea2deea35904960f3406a115aa", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "5f1826d04c7f7befc2dfa372c760ab5596619a99" + "revision" : "43acdd60e045a98853997436defe346804e9ff34" } }, { diff --git a/Package.swift b/Package.swift index 38b5b40..87eacb1 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "5f1826d04c7f7befc2dfa372c760ab5596619a99"), + revision: "43acdd60e045a98853997436defe346804e9ff34"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 0adccb0..59daee1 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/5f1826d04c7f7befc2dfa372c760ab5596619a99/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/43acdd60e045a98853997436defe346804e9ff34/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From db438e0c1c6ade441c61bb548a33df2366522a3f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:52:43 +0800 Subject: [PATCH 48/67] feat: manage package lifecycle actions in the CLI --- Documentation/Reference/CLI.md | 61 ++- .../Reference/Schemas/install.schema.json | 3 + .../Reference/Schemas/lifecycle.schema.json | 237 ++++++++++ Sources/CLI/BundleCommands.swift | 50 ++- Sources/CLI/ComponentCommands.swift | 24 +- Sources/CLI/EntryPoint.swift | 1 + Sources/CLI/InstructionCommands.swift | 55 ++- Sources/CLI/InstructionReports.swift | 4 +- Sources/CLI/LifecycleCommands.swift | 114 ++--- Sources/CLI/MarketplaceCommands.swift | 69 +-- Sources/CLI/MarketplaceDeployment.swift | 56 ++- Sources/CLI/MarketplaceGraphCommands.swift | 34 +- Sources/CLI/PackageLifecycleApply.swift | 142 ++++++ Sources/CLI/PackageLifecycleCommands.swift | 407 ++++++++++++++++++ Sources/CLI/PackageLifecycleReports.swift | 198 +++++++++ Sources/CLI/SkillCommands.swift | 23 +- .../CLITests/MarketplaceExecutableTests.swift | 71 +++ .../PackageLifecycleExecutableTests.swift | 264 ++++++++++++ 18 files changed, 1628 insertions(+), 185 deletions(-) create mode 100644 Documentation/Reference/Schemas/lifecycle.schema.json create mode 100644 Sources/CLI/PackageLifecycleApply.swift create mode 100644 Sources/CLI/PackageLifecycleCommands.swift create mode 100644 Sources/CLI/PackageLifecycleReports.swift create mode 100644 Tests/CLITests/PackageLifecycleExecutableTests.swift diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index e921fb4..accb362 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -63,6 +63,13 @@ 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] @@ -96,7 +103,7 @@ 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 | +| `--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` | @@ -129,6 +136,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 @@ -1000,6 +1058,7 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | `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` | +| `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` | diff --git a/Documentation/Reference/Schemas/install.schema.json b/Documentation/Reference/Schemas/install.schema.json index 989b035..c26dc14 100644 --- a/Documentation/Reference/Schemas/install.schema.json +++ b/Documentation/Reference/Schemas/install.schema.json @@ -41,6 +41,9 @@ "instructions": { "$ref": "instructions.schema.json#/$defs/changes" }, + "lifecycle": { + "$ref": "lifecycle.schema.json#/$defs/package" + }, "components": { "type": "array", "items": { 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/Sources/CLI/BundleCommands.swift b/Sources/CLI/BundleCommands.swift index 83802fb..831f549 100644 --- a/Sources/CLI/BundleCommands.swift +++ b/Sources/CLI/BundleCommands.swift @@ -6,8 +6,10 @@ 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]) + subcommands: [ + CreateAuthorProject.self, PackAuthorProject.self, ExportNativePlugin.self, + ExportBundle.self, InspectBundle.self, ImportBundle.self, + ]) } struct ExportBundle: ParsableCommand { @@ -73,19 +75,29 @@ struct InspectBundle: ParsableCommand { } } -struct ImportBundle: ParsableCommand { +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() throws { + func run() async throws { let bundle = try BundleOperations.inspect(Data(contentsOf: URL(fileURLWithPath: file))) - let preview = try BundleOperations.previewImport( - bundle, selections: installation.selections(in: bundle), - scope: installation.options.location.scope, environment: RuntimeEnvironment(), - replace: installation.replace) - try installation.finish(preview) + 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) + } } } @@ -103,26 +115,26 @@ struct BundleInstallOptions: ParsableArguments { let ids = component.isEmpty ? bundle.components.map(\.id) : component return ids.map { BundleImportSelection(componentID: $0, targets: agent) } } - - func finish(_ preview: BundleImportPreview) throws { - try options.finishImport(preview, bindings: bindings) - } } extension UpdateOptions { - func finishImport(_ preview: BundleImportPreview, bindings: BindingOptions) throws { + 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 { - _ = try BundleOperations.withPreparedImport(preview, bindingProvider: bindings.provider()) { - try $0.apply() - } - } else if !json { + 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/ComponentCommands.swift b/Sources/CLI/ComponentCommands.swift index b0dc4c1..20d6cf8 100644 --- a/Sources/CLI/ComponentCommands.swift +++ b/Sources/CLI/ComponentCommands.swift @@ -215,7 +215,7 @@ func requireCommittedInspection(_ inspection: ScopeInspection) throws { } } -struct RemoveComponents: ParsableCommand { +struct RemoveComponents: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "remove", abstract: "Remove an exact managed component or occurrence.") @OptionGroup var selection: ComponentSelector @@ -223,19 +223,21 @@ struct RemoveComponents: ParsableCommand { @OptionGroup var agents: AgentOptions @OptionGroup var writing: ComponentWriteOptions - func run() throws { - let result = try withRecovery { - let inspection = try UpdateOperations.inspect(scope: location.scope) + 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.withPreparedUpdate( - writing.request(request), scope: location.scope, - bindingProvider: writing.bindings.provider() - ) { try $0.apply() } + 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) } - 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/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index f3652b4..c8e98a2 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -30,6 +30,7 @@ struct Agents: ParsableCommand { Skills.self, InstructionsCommand.self, Watch.self, Manifest.self, Install.self, Update.self, Doctor.self, ComponentsCommand.self, ImportCommand.self, MCPCommand.self, BundleCommand.self, MarketplaceCommand.self, CacheCommand.self, PolicyCommand.self, AuditCommand.self, + LifecycleCommand.self, ] ) diff --git a/Sources/CLI/InstructionCommands.swift b/Sources/CLI/InstructionCommands.swift index 9262654..3427e52 100644 --- a/Sources/CLI/InstructionCommands.swift +++ b/Sources/CLI/InstructionCommands.swift @@ -1,6 +1,7 @@ import AgentsCore import AgentsInstructions import AgentsManifest +import AgentsUpdates import ArgumentParser import Foundation @@ -131,7 +132,7 @@ struct ListInstructions: ParsableCommand { } } -struct RemoveInstructions: ParsableCommand { +struct RemoveInstructions: AsyncParsableCommand { static let configuration = CommandConfiguration( 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.") @@ -145,21 +146,25 @@ 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.instructionNotes($0) - Terminal.instructionTargets($0, 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) + } + 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.updatedInstructions(result, paths: location.paths) - 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.", discussion: "Use --agent to set the recipient list for all sections in this scope.") @@ -173,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) } } } diff --git a/Sources/CLI/InstructionReports.swift b/Sources/CLI/InstructionReports.swift index bcc74b2..b8f9529 100644 --- a/Sources/CLI/InstructionReports.swift +++ b/Sources/CLI/InstructionReports.swift @@ -252,8 +252,10 @@ struct InstallReport: Encodable { let skills: [RestoredSkill] let instructions: InstructionChanges let components: [ComponentChangeItem] + let lifecycle: PackageLifecycleReport? - init(_ result: UpdateApplyResult) { + init(_ result: UpdateApplyResult, lifecycle: PackageLifecycleReport?) { + self.lifecycle = lifecycle scope = result.report.scope.rawValue skills = result.installedSkills.map(RestoredSkill.init) instructions = InstructionChanges(result.report.instructions) diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index 5e02bac..cf37c7f 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -5,7 +5,7 @@ import AgentsUpdates import ArgumentParser import Foundation -struct Install: ParsableCommand { +struct Install: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "install", abstract: "Restore all components using exact pins and recipients from the lock.") @@ -14,12 +14,19 @@ struct Install: ParsableCommand { @OptionGroup var bindings: BindingOptions @Flag(help: "Print the versioned JSON report.") var json = false - func run() throws { - let result = try withRecovery { - try UpdateOperations.restore(scope: location.scope, bindingProvider: bindings.provider()) + func run() async throws { + let review = try previewAfterRecovery(scope: location.scope) { + try UpdateOperations.previewLifecycle( + UpdateRequest(operation: .restore), intent: .install, scope: location.scope) } + 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)) + try Terminal.json(InstallReport(result, lifecycle: lifecycle)) } else { Terminal.instructionNotes(result.report.instructions) if result.installedSkills.isEmpty { @@ -52,47 +59,6 @@ struct UpdateOptions: ParsableArguments { if json && apply { throw ValidationError("--json is for previews; remove --apply or --json") } } - func updateSkills(names: [String] = []) throws -> [UpdateResult] { - func operation() throws -> [UpdateResult] { - try SkillOperations.updateInstalled( - scope: location.scope, skillNames: names, apply: apply, - beforeApply: { results in - Terminal.differences(results, paths: location.paths) - }) - } - return try apply ? withRecovery(operation) : operation() - } - - 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 - { - func operation() throws -> InstructionUpdateReport { - try InstructionOperations.updateInstalled( - scope: location.scope, agents: agents, apply: apply, replace: replace, - beforeApply: { result in - Terminal.instructionDifferences(result, paths: location.paths) - }) - } - return try apply ? withRecovery(operation) : operation() - } - - func finishInstructions(_ result: InstructionUpdateReport) { - if apply { - Terminal.updatedInstructions(result, paths: location.paths) - } else { - Terminal.instructionDifferences(result, paths: location.paths) - previewNotice(changed: result.hasChanges && result.conflicts.isEmpty) - } - } - func previewNotice(changed: Bool) { if !apply && changed { Terminal.write("Preview only. Run again with --apply to write these changes.\n") @@ -100,29 +66,30 @@ struct UpdateOptions: ParsableArguments { } } -struct Update: ParsableCommand { +struct Update: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "update", 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( - writing.request(), scope: options.location.scope, - bindingProvider: writing.bindings.provider() - ) { 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.componentChanges(receipt.report.components, paths: paths, applied: true) - Terminal.promptReminder(receipt.report.instructions.changedPrompts) } else { let report = try UpdateOperations.preview(writing.request(), scope: options.location.scope) if options.json { @@ -135,19 +102,31 @@ struct Update: ParsableCommand { } } -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) + } + 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)) } } @@ -215,7 +194,8 @@ struct Doctor: ParsableCommand { 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) { + for finding in audit.pendingMarketplacePolicy?.findings ?? [] + where !findings.contains(finding) { findings.append(finding) } checks = diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift index d7943f4..bad9ab1 100644 --- a/Sources/CLI/MarketplaceCommands.swift +++ b/Sources/CLI/MarketplaceCommands.swift @@ -289,7 +289,7 @@ struct OutdatedPackages: ParsableCommand { } } -struct UpgradeMarketPackage: ParsableCommand { +struct UpgradeMarketPackage: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "upgrade", abstract: "Review a newer release using this project's installed selections.") @@ -302,7 +302,7 @@ struct UpgradeMarketPackage: ParsableCommand { @OptionGroup var options: UpdateOptions @OptionGroup var bindings: BindingOptions - func run() throws { + func run() async throws { let scope = options.location.scope let inspection = try committedMarketplaceInspection(scope) let requirement = try version.requirement() @@ -313,7 +313,7 @@ struct UpgradeMarketPackage: ParsableCommand { || inspection.marketplaceGraph?.roots.contains(where: { $0.intent.name == name }) == true || version.requirementExpression != nil || !members.member.isEmpty { - try options.finishMarketplace( + try await options.finishMarketplace( .upgrade(name, requirement: requirement, selections: try members.selections(in: scope)), bindings: bindings, lockOnly: lockOnly, hostedAccess: hosted.access()) return @@ -341,7 +341,7 @@ struct UpgradeMarketPackage: ParsableCommand { let verified = try MarketplaceOperations.acquire(release, scope: scope) let bundle = try verified.inspectBundle() if bundle.package.dependencies != nil { - try options.finishMarketplace( + try await options.finishMarketplace( .upgrade(name, requirement: .exact(release.coordinate.version)), bindings: bindings, hostedAccess: hosted.access()) return @@ -352,12 +352,17 @@ struct UpgradeMarketPackage: ParsableCommand { "No installed components match this release. Choose its components with marketplace install." ) } - let preview = try verified.previewImport(as: name, selections: selections, scope: scope) - try options.finishImport(preview, bindings: bindings) + 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: ParsableCommand { +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 @@ -391,7 +396,7 @@ struct InstallMarketPackage: ParsableCommand { _ = try version.requirement() } - func run() throws { + func run() async throws { let scope = options.location.scope let name = alias ?? package let registration = try source.registration(in: scope) @@ -422,9 +427,15 @@ struct InstallMarketPackage: ParsableCommand { let selections = ids.map { BundleImportSelection(componentID: $0, targets: members.agent) } - let preview = try verified.previewImport( - as: name, selections: selections, scope: scope, replace: replace) - try options.finishImport(preview, bindings: bindings) + 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 } } @@ -437,11 +448,11 @@ struct InstallMarketPackage: ParsableCommand { selections: selections) } if metadataOnly { - try options.finishMarketplace( + try await options.finishMarketplace( .install(root([])), bindings: bindings, replace: replace, lockOnly: lockOnly, hostedAccess: access) } else if let selected = try members.selections(in: scope) { - try options.finishMarketplace( + try await options.finishMarketplace( .install(root(selected)), bindings: bindings, replace: replace, lockOnly: lockOnly, hostedAccess: access) } else { @@ -470,7 +481,7 @@ struct InstallMarketPackage: ParsableCommand { try MarketplaceMemberSelection( package: package, member: $0.marketplaceKey, targets: members.agent) } - try options.finishMarketplace( + try await options.finishMarketplace( .install(root(selections)), bindings: bindings, replace: replace, lockOnly: lockOnly, hostedAccess: access ) { resolution in @@ -482,7 +493,7 @@ struct InstallMarketPackage: ParsableCommand { } } -struct RemoveMarketPackage: ParsableCommand { +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 @@ -492,33 +503,29 @@ struct RemoveMarketPackage: ParsableCommand { @OptionGroup var options: UpdateOptions @OptionGroup var bindings: BindingOptions - func run() throws { + 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 options.finishMarketplace( + try await options.finishMarketplace( .remove(name), bindings: bindings, lockOnly: lockOnly, hostedAccess: hosted.access()) return } let request = MarketplaceOperations.removalRequest(for: name) - let report = try UpdateOperations.preview(request, scope: scope) - if options.json { - try Terminal.json(UpdateReport(report)) - } else { - Terminal.updateDifferences(report, paths: options.location.paths) - } if options.apply { - _ = try withRecovery { - try UpdateOperations.withPreparedUpdate( - request, scope: scope, bindingProvider: bindings.provider() - ) { - try $0.apply(ifUnchangedFrom: report.displayedFingerprint) - } + 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) } - } else if !options.json { - options.previewNotice(changed: report.hasChanges) } } } diff --git a/Sources/CLI/MarketplaceDeployment.swift b/Sources/CLI/MarketplaceDeployment.swift index cb9c04f..da1ecae 100644 --- a/Sources/CLI/MarketplaceDeployment.swift +++ b/Sources/CLI/MarketplaceDeployment.swift @@ -18,23 +18,32 @@ struct MarketplacePendingReport: Encodable { } } -struct ResolvePendingMarketPackages: ParsableCommand { +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() throws { try options.finishPendingLock(.reconcile, hostedAccess: hosted.access()) } + 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 } - ) throws { - let preview = try MarketplaceOperations.previewLockOnly( - request, scope: location.scope, hostedAccess: hostedAccess) + ) 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)) @@ -46,34 +55,41 @@ extension UpdateOptions { } Terminal.write("Pending deployment: " + preview.report.pendingDeployment.digest + "\n") } - if apply { - _ = try MarketplaceOperations.writeLockOnly(preview) + if let review { + try await applyLifecycle(review, scope: location.scope) } else if !json { previewNotice(changed: preview.report.hasChanges) } } } -struct DeployLockedMarketPackages: ParsableCommand { +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() throws { - let preview = try MarketplaceOperations.previewFrozenDeployment( - scope: options.location.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) } + func run() async throws { + let scope = options.location.scope if options.apply { - _ = try MarketplaceOperations.deployFrozen(preview, bindingProvider: bindings.provider()) - } else if !options.json { - options.previewNotice(changed: preview.report.hasChanges) + 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 index dc7c38c..251fe7f 100644 --- a/Sources/CLI/MarketplaceGraphCommands.swift +++ b/Sources/CLI/MarketplaceGraphCommands.swift @@ -201,18 +201,36 @@ extension MarketplaceResolution { } } +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 } - ) throws { + ) async throws { if lockOnly { - try finishPendingLock(request, hostedAccess: hostedAccess, checking: check) + try await finishPendingLock(request, hostedAccess: hostedAccess, checking: check) return } - let preview = try MarketplaceOperations.previewResolution( - request, scope: location.scope, replace: replace, hostedAccess: hostedAccess) + 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)) @@ -224,12 +242,8 @@ extension UpdateOptions { Terminal.updateDifferences(preview.report, paths: location.paths) } if let conflict = preview.ownershipConflict { throw CoreError.invalidState(conflict) } - if apply { - _ = try MarketplaceOperations.withPreparedResolution( - preview, bindingProvider: bindings.provider() - ) { - try $0.apply(ifUnchangedFrom: preview.report.displayedFingerprint) - } + 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/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/SkillCommands.swift b/Sources/CLI/SkillCommands.swift index acbf90c..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 @@ -99,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.") @@ -111,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/Tests/CLITests/MarketplaceExecutableTests.swift b/Tests/CLITests/MarketplaceExecutableTests.swift index dd58679..5a2e0a8 100644 --- a/Tests/CLITests/MarketplaceExecutableTests.swift +++ b/Tests/CLITests/MarketplaceExecutableTests.swift @@ -276,6 +276,77 @@ struct MarketplaceExecutableTests { #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 } 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)), + ] +} From b98f7317632cc7fe918d72d922db5a2a19d72099 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 02:58:14 +0800 Subject: [PATCH 49/67] feat: add package source credential checks and export --- Documentation/Reference/CLI.md | 38 ++++- .../Reference/Schemas/auth-check.schema.json | 19 +++ Sources/CLI/AuthCommand.swift | 142 ++++++++++++++++++ Sources/CLI/EntryPoint.swift | 3 +- Sources/CLI/Terminal.swift | 1 + Tests/CLITests/AuthExecutableTests.swift | 68 +++++++++ 6 files changed, 267 insertions(+), 4 deletions(-) create mode 100644 Documentation/Reference/Schemas/auth-check.schema.json create mode 100644 Sources/CLI/AuthCommand.swift create mode 100644 Tests/CLITests/AuthExecutableTests.swift diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index ad43052..c72de8a 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -38,6 +38,9 @@ agents bundle plugin --target [--marketplace ] [--output --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] @@ -71,8 +74,8 @@ agents audit --file --strip [--scope project|user] [--apply] ``` `agents --help`, `agents skills --help`, `agents instructions --help`, -`agents watch --help`, `agents manifest --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 @@ -105,7 +108,7 @@ Examples: | `--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`; `manifest dump` requires it | +| `--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. | Skill and instruction recipients are `codex`, `claude-code`, `cursor`, `gemini-cli`, `opencode`, and `antigravity`. Cursor instructions use @@ -374,6 +377,34 @@ 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. An emitted report exits 0, including `refused` and +`indeterminate`. 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. @@ -1007,6 +1038,7 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | `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` | 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/Sources/CLI/AuthCommand.swift b/Sources/CLI/AuthCommand.swift new file mode 100644 index 0000000..749a6bb --- /dev/null +++ b/Sources/CLI/AuthCommand.swift @@ -0,0 +1,142 @@ +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") + } + } + } + + 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/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index f3652b4..7f00c32 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -29,7 +29,8 @@ struct Agents: ParsableCommand { subcommands: [ Skills.self, InstructionsCommand.self, Watch.self, Manifest.self, Install.self, Update.self, Doctor.self, ComponentsCommand.self, ImportCommand.self, MCPCommand.self, BundleCommand.self, - MarketplaceCommand.self, CacheCommand.self, PolicyCommand.self, AuditCommand.self, + MarketplaceCommand.self, AuthCommand.self, CacheCommand.self, PolicyCommand.self, + AuditCommand.self, ] ) diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 13ff6b2..118e545 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -163,6 +163,7 @@ enum Terminal { static func failureMessage(_ error: Error) -> String { if let cache = error as? AcquisitionCacheError { return cache.localizedDescription } + if let source = error as? SourceAccessError { return source.localizedDescription } if let error = error as? UpdateApplyError { return updateFailureMessage(error.disposition, underlyingError: error.underlyingError) } diff --git a/Tests/CLITests/AuthExecutableTests.swift b/Tests/CLITests/AuthExecutableTests.swift new file mode 100644 index 0000000..cb30bc7 --- /dev/null +++ b/Tests/CLITests/AuthExecutableTests.swift @@ -0,0 +1,68 @@ +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 source = try fixture.success([ + "auth", "check", "--source", "demo@tag:release/v1", "--json", + ]).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 host = try fixture.success([ + "auth", "check", "--host", "packages.example.invalid:8443", "--json", + ]).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.success(["auth", "check", "--host", "GitHub.COM:443"]) + #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")) + } +} From f55beb0ea680fab0e75701dc75de9769afcf7547 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:08:08 +0800 Subject: [PATCH 50/67] fix: signal unavailable source credentials to callers --- Documentation/Reference/CLI.md | 5 +++-- Sources/CLI/AuthCommand.swift | 6 ++++++ Tests/CLITests/AuthExecutableTests.swift | 15 ++++++++++----- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index c72de8a..ce2ada8 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -395,8 +395,9 @@ 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. An emitted report exits 0, including `refused` and -`indeterminate`. With `--json`, the `validation` property is omitted when +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 diff --git a/Sources/CLI/AuthCommand.swift b/Sources/CLI/AuthCommand.swift index 749a6bb..4f2fe5e 100644 --- a/Sources/CLI/AuthCommand.swift +++ b/Sources/CLI/AuthCommand.swift @@ -72,6 +72,12 @@ struct AuthCommand: ParsableCommand { 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 + } } } diff --git a/Tests/CLITests/AuthExecutableTests.swift b/Tests/CLITests/AuthExecutableTests.swift index cb30bc7..fc9e305 100644 --- a/Tests/CLITests/AuthExecutableTests.swift +++ b/Tests/CLITests/AuthExecutableTests.swift @@ -17,9 +17,11 @@ struct AuthExecutableTests { demo: {path: '\(fixture.source.path)'} """, scope: "user") - let source = try fixture.success([ + let sourceResult = try fixture.run([ "auth", "check", "--source", "demo@tag:release/v1", "--json", - ]).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) @@ -40,14 +42,17 @@ struct AuthExecutableTests { #expect(user["transport"] as? String == "local") #expect(user["validation"] as? String == "indeterminate") - let host = try fixture.success([ + let hostResult = try fixture.run([ "auth", "check", "--host", "packages.example.invalid:8443", "--json", - ]).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.success(["auth", "check", "--host", "GitHub.COM:443"]) + 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 [ From d232207d68cac6b03d2119708201135bcfa9fa57 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:13:36 +0800 Subject: [PATCH 51/67] feat: use the configured MCP registry by default --- Documentation/Reference/CLI.md | 10 ++++++---- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- Sources/CLI/MCPRegistryCommands.swift | 4 ++-- 6 files changed, 13 insertions(+), 11 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index be01cb2..25e4c7d 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -479,9 +479,11 @@ agents marketplace upgrade onboarding --apply ## MCP Registry -Use `mcp search` to browse the public registry, then `mcp show` to inspect an exact version, -its numbered installation choices and input requirements. Pass `--registry ` -to use a private registry and `--token-env ` when it needs bearer authentication. +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. @@ -821,7 +823,7 @@ current directory and user scope uses HOME. | 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/f3649813896e1086d3fdf66642bbc60292a70695/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/574583e43c6375f7fd7d57700103569cffafcf36/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 8d13839..b16ecec 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/f3649813896e1086d3fdf66642bbc60292a70695/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/574583e43c6375f7fd7d57700103569cffafcf36/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. diff --git a/Package.resolved b/Package.resolved index 9cb954d..b050444 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "bc0a3b16aa5f5f6e4e7827a5f4597f181bda87cebb7bfe2fb87093798c3cc735", + "originHash" : "d3b5ac7afdc589868f799e58d6ee4e837b88fb3dd6a135605a61beda459939a7", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "f3649813896e1086d3fdf66642bbc60292a70695" + "revision" : "574583e43c6375f7fd7d57700103569cffafcf36" } }, { diff --git a/Package.swift b/Package.swift index 40cd780..3a5b067 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "f3649813896e1086d3fdf66642bbc60292a70695"), + revision: "574583e43c6375f7fd7d57700103569cffafcf36"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 440b688..ed198a0 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/f3649813896e1086d3fdf66642bbc60292a70695/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/574583e43c6375f7fd7d57700103569cffafcf36/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. diff --git a/Sources/CLI/MCPRegistryCommands.swift b/Sources/CLI/MCPRegistryCommands.swift index 967e23b..1033ac5 100644 --- a/Sources/CLI/MCPRegistryCommands.swift +++ b/Sources/CLI/MCPRegistryCommands.swift @@ -4,13 +4,13 @@ import ArgumentParser import Foundation struct RegistryOptions: ParsableArguments { - @Option(help: "MCP Registry v0.1 base URL. Defaults to the public MCP Registry.") + @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 .official } + guard let registry else { return try .configured() } guard let url = URL(string: registry) else { throw ValidationError("Invalid registry URL") } return try MCPRegistry(endpoint: url) } From a1d943c0588e76c788b50e0e3b80081929b2b4aa Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:20:22 +0800 Subject: [PATCH 52/67] build: pin core package actions and source routing --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 104030d..6ce2bab 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -913,7 +913,7 @@ current directory and user scope uses HOME. | 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/574583e43c6375f7fd7d57700103569cffafcf36/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/9fd1348b56c56afde52463d4e97990f500149f67/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index b16ecec..3c74dee 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/574583e43c6375f7fd7d57700103569cffafcf36/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/9fd1348b56c56afde52463d4e97990f500149f67/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. diff --git a/Package.resolved b/Package.resolved index b050444..3285904 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "d3b5ac7afdc589868f799e58d6ee4e837b88fb3dd6a135605a61beda459939a7", + "originHash" : "5cabf89f4804153c1bec369cf6aa9ac9fa2b31ab1513d090b796b4e931872338", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "574583e43c6375f7fd7d57700103569cffafcf36" + "revision" : "9fd1348b56c56afde52463d4e97990f500149f67" } }, { diff --git a/Package.swift b/Package.swift index 3a5b067..9e96bb2 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "574583e43c6375f7fd7d57700103569cffafcf36"), + revision: "9fd1348b56c56afde52463d4e97990f500149f67"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index ed198a0..abb8ab9 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/574583e43c6375f7fd7d57700103569cffafcf36/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/9fd1348b56c56afde52463d4e97990f500149f67/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 4f29db2e013378fad9ee5710cbae000f4b9a7877 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:34:10 +0800 Subject: [PATCH 53/67] feat: use trusted operator settings for package sources --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- Sources/CLI/Terminal.swift | 3 +++ 6 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 6ce2bab..a3e1d84 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -913,7 +913,7 @@ current directory and user scope uses HOME. | 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/9fd1348b56c56afde52463d4e97990f500149f67/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/0b334435a93a455cebaf8134e030cee4f629d5e9/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 3c74dee..2a63ba8 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/9fd1348b56c56afde52463d4e97990f500149f67/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/0b334435a93a455cebaf8134e030cee4f629d5e9/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. diff --git a/Package.resolved b/Package.resolved index 3285904..5db2fe0 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "5cabf89f4804153c1bec369cf6aa9ac9fa2b31ab1513d090b796b4e931872338", + "originHash" : "a72822cec93d8028433c810887feb4094eef91aa6848530858e1bb20c9fe1374", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "9fd1348b56c56afde52463d4e97990f500149f67" + "revision" : "0b334435a93a455cebaf8134e030cee4f629d5e9" } }, { diff --git a/Package.swift b/Package.swift index 9e96bb2..1aaf7fb 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "9fd1348b56c56afde52463d4e97990f500149f67"), + revision: "0b334435a93a455cebaf8134e030cee4f629d5e9"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index abb8ab9..6e3062e 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/9fd1348b56c56afde52463d4e97990f500149f67/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/0b334435a93a455cebaf8134e030cee4f629d5e9/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. diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 118e545..64319dc 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -155,6 +155,8 @@ enum Terminal { "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" } @@ -164,6 +166,7 @@ enum Terminal { static func failureMessage(_ error: Error) -> String { 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) } From 3a17dffcf7b5f6693a5b9f1357b91865f2bf7676 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:38:53 +0800 Subject: [PATCH 54/67] docs: include Antigravity in the supported clients --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6e3062e..39bfb51 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ 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, and OpenCode through +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 From 2d436c1c1178b8f0b6631f10cb8badc184569e36 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:54:48 +0800 Subject: [PATCH 55/67] fix: suppress unowned skill update previews on apply --- Sources/CLI/LifecycleCommands.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index cf37c7f..44d7b18 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -115,7 +115,9 @@ struct UpdateSkills: AsyncParsableCommand { try UpdateOperations.previewLifecycle( UpdateRequest(kinds: [.skills], names: names), intent: .update, scope: scope) } - Terminal.differences(review.report.skills, paths: options.location.paths) + 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) } From b7fdb52330cad863a2a82cb01f18e1bf9ed7a572 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:54:49 +0800 Subject: [PATCH 56/67] fix: accept categories for native marketplace export --- Documentation/Reference/CLI.md | 4 +-- Sources/CLI/AuthorPackageCommands.swift | 9 +++++- .../CLITests/MarketplaceExecutableTests.swift | 29 +++++++++++++++++++ 3 files changed, 39 insertions(+), 3 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index a3e1d84..fee6e71 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -34,7 +34,7 @@ agents components remove [--kind ] [--identity ] [--occurrence 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 ] [--output ] [--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] @@ -500,7 +500,7 @@ 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. +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 diff --git a/Sources/CLI/AuthorPackageCommands.swift b/Sources/CLI/AuthorPackageCommands.swift index fd1f170..d20c697 100644 --- a/Sources/CLI/AuthorPackageCommands.swift +++ b/Sources/CLI/AuthorPackageCommands.swift @@ -66,6 +66,7 @@ struct ExportNativePlugin: ParsableCommand { 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? @@ -75,9 +76,15 @@ struct ExportNativePlugin: ParsableCommand { 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) }) + 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") diff --git a/Tests/CLITests/MarketplaceExecutableTests.swift b/Tests/CLITests/MarketplaceExecutableTests.swift index 5a2e0a8..247ba42 100644 --- a/Tests/CLITests/MarketplaceExecutableTests.swift +++ b/Tests/CLITests/MarketplaceExecutableTests.swift @@ -2,6 +2,35 @@ 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 graphResolutionUpgradeAndRemovalUseTheNamedCatalog() throws { let fixture = try CLIFixture() let market = try MarketplaceFixture(fixture) From dff433f142901f04c57c9a23407ccbbd86cd1b3d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:21:47 +0800 Subject: [PATCH 57/67] fix: apply the selected scope to package publication --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- Sources/CLI/MarketplaceCommands.swift | 2 +- .../CLITests/MarketplaceExecutableTests.swift | 23 +++++++++++++++++++ 7 files changed, 30 insertions(+), 7 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index fee6e71..c74c668 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -913,7 +913,7 @@ current directory and user scope uses HOME. | 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/0b334435a93a455cebaf8134e030cee4f629d5e9/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/891fcdc282a2ec0f72439a5f5c6f1116bbb486e9/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 2a63ba8..c559591 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/0b334435a93a455cebaf8134e030cee4f629d5e9/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/891fcdc282a2ec0f72439a5f5c6f1116bbb486e9/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. diff --git a/Package.resolved b/Package.resolved index 5db2fe0..efacc0a 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "a72822cec93d8028433c810887feb4094eef91aa6848530858e1bb20c9fe1374", + "originHash" : "35dd3da034c65540bf987870a88d0a256d400f331c75504b240cfefc3f1640ab", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "0b334435a93a455cebaf8134e030cee4f629d5e9" + "revision" : "891fcdc282a2ec0f72439a5f5c6f1116bbb486e9" } }, { diff --git a/Package.swift b/Package.swift index 1aaf7fb..bac01f9 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "0b334435a93a455cebaf8134e030cee4f629d5e9"), + revision: "891fcdc282a2ec0f72439a5f5c6f1116bbb486e9"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 39bfb51..22d4ea9 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/0b334435a93a455cebaf8134e030cee4f629d5e9/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/891fcdc282a2ec0f72439a5f5c6f1116bbb486e9/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. diff --git a/Sources/CLI/MarketplaceCommands.swift b/Sources/CLI/MarketplaceCommands.swift index bad9ab1..1213e0e 100644 --- a/Sources/CLI/MarketplaceCommands.swift +++ b/Sources/CLI/MarketplaceCommands.swift @@ -194,7 +194,7 @@ struct PublishPackage: ParsableCommand { } let published = try MarketplaceOperations.publishBundle( Data(contentsOf: URL(fileURLWithPath: archive)), to: URL(fileURLWithPath: address.location), - summary: summary) + summary: summary, scope: location.scope) Terminal.write( "\(Terminal.line(published.coordinate.package)) \(Terminal.line(published.coordinate.version)) \(published.archiveDigest)\n" ) diff --git a/Tests/CLITests/MarketplaceExecutableTests.swift b/Tests/CLITests/MarketplaceExecutableTests.swift index 247ba42..135de85 100644 --- a/Tests/CLITests/MarketplaceExecutableTests.swift +++ b/Tests/CLITests/MarketplaceExecutableTests.swift @@ -31,6 +31,29 @@ struct MarketplaceExecutableTests { #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) From 268ccc1096ca2531c676d3f52645690c042d0e0f Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:37:02 +0800 Subject: [PATCH 58/67] build: pin portable package source policy --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index c74c668..8f59166 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -913,7 +913,7 @@ current directory and user scope uses HOME. | 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/891fcdc282a2ec0f72439a5f5c6f1116bbb486e9/Documentation/Reference/Manifest.md), +uses the [manifest format](https://github.com/agents-tools/core/blob/18509dac75dc1b72e9ef25da7debaa829d1121f0/Documentation/Reference/Manifest.md), a versioned YAML mapping with required `version: 1`. Sources are named mappings; components are ordered sequences. Unknown structural fields produce located diagnostics. The declaration schema and parser are owned by core. Lifecycle diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index c559591..8274c2c 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/891fcdc282a2ec0f72439a5f5c6f1116bbb486e9/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/18509dac75dc1b72e9ef25da7debaa829d1121f0/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. diff --git a/Package.resolved b/Package.resolved index efacc0a..9f71213 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "35dd3da034c65540bf987870a88d0a256d400f331c75504b240cfefc3f1640ab", + "originHash" : "633a0639a666d9974eaa4a30d186e6e2ec109fd3798186bef048d957b2b9ea75", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "891fcdc282a2ec0f72439a5f5c6f1116bbb486e9" + "revision" : "18509dac75dc1b72e9ef25da7debaa829d1121f0" } }, { diff --git a/Package.swift b/Package.swift index bac01f9..0222711 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "891fcdc282a2ec0f72439a5f5c6f1116bbb486e9"), + revision: "18509dac75dc1b72e9ef25da7debaa829d1121f0"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 22d4ea9..583f24f 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/891fcdc282a2ec0f72439a5f5c6f1116bbb486e9/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/18509dac75dc1b72e9ef25da7debaa829d1121f0/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 3ae8edff69fb62efd9e11b4f2dc68ef2a5658380 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:44:35 +0800 Subject: [PATCH 59/67] build: use verified MCP package transport --- Documentation/Reference/CLI.md | 2 +- Documentation/Reference/ManifestDump.md | 2 +- Package.resolved | 4 ++-- Package.swift | 2 +- README.md | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 8f59166..1db688a 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -913,7 +913,7 @@ current directory and user scope uses HOME. | 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/18509dac75dc1b72e9ef25da7debaa829d1121f0/Documentation/Reference/Manifest.md), +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 diff --git a/Documentation/Reference/ManifestDump.md b/Documentation/Reference/ManifestDump.md index 8274c2c..c863350 100644 --- a/Documentation/Reference/ManifestDump.md +++ b/Documentation/Reference/ManifestDump.md @@ -2,7 +2,7 @@ `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/18509dac75dc1b72e9ef25da7debaa829d1121f0/Documentation/Reference/Manifest.md#bounds-and-dump), +are core's [Bounds and Dump](https://github.com/agents-tools/core/blob/25d965fa18465f60341ba81bff4a511766d7659b/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. diff --git a/Package.resolved b/Package.resolved index 9f71213..eb5a29a 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "633a0639a666d9974eaa4a30d186e6e2ec109fd3798186bef048d957b2b9ea75", + "originHash" : "554c9ce35e526035938d09499ed6b557a437d0961b0b7210e542ff0b4ade6dd4", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "18509dac75dc1b72e9ef25da7debaa829d1121f0" + "revision" : "25d965fa18465f60341ba81bff4a511766d7659b" } }, { diff --git a/Package.swift b/Package.swift index 0222711..b6baf35 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "18509dac75dc1b72e9ef25da7debaa829d1121f0"), + revision: "25d965fa18465f60341ba81bff4a511766d7659b"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 583f24f..84e8345 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,7 @@ 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/18509dac75dc1b72e9ef25da7debaa829d1121f0/Documentation/Reference/Manifest.md) +`~/.agents/agents.yaml` for user scope. The [manifest format](https://github.com/agents-tools/core/blob/25d965fa18465f60341ba81bff4a511766d7659b/Documentation/Reference/Manifest.md) uses a versioned YAML mapping. `agents manifest dump --json` prints the local declaration as a JSON object with source locations without resolving sources. From 6b833e3034aeb2fc8a869308f60454c8ab9db4a6 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:40:33 +0800 Subject: [PATCH 60/67] ci: install SQLite for Linux CLI validation --- .github/ci/linux-tests.Dockerfile | 13 +++++++++++++ .github/ci/test-linux.sh | 14 ++++++++++++++ .github/swift-package.json | 15 +++++++-------- README.md | 3 +++ 4 files changed, 37 insertions(+), 8 deletions(-) create mode 100644 .github/ci/linux-tests.Dockerfile create mode 100644 .github/ci/test-linux.sh 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 69406c7..4ffd88a 100644 --- a/.github/swift-package.json +++ b/.github/swift-package.json @@ -3,12 +3,11 @@ {"name": "macos-26-xcode-26.6", "runner": "macos-26", "xcode": "26.6"} ], "demo": {"product": "agents"}, - "platforms": { - "linux": [ - { - "name": "linux-swift-6.4.1", - "image": "swift:6.4.1-noble@sha256:6304481cf2717966b7ba175162e397ea2f2cc3161909f2b2a5cf40036079a0f7" - } - ] - } + "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/README.md b/README.md index 9946c60..e904a36 100644 --- a/README.md +++ b/README.md @@ -163,6 +163,7 @@ for supported profiles, selection options and report schemas. - 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 @@ -231,6 +232,8 @@ declared in the organization's [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. From 13fc671ebd85e82780452afe2f424f67e1a1c810 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:40:33 +0800 Subject: [PATCH 61/67] fix: migrate existing user configuration and refresh the project ledger --- .agent/agents.resolved | 48 +----------- CHANGELOG.md | 5 +- Documentation/Reference/CLI.md | 19 ++++- Sources/CLI/ManifestCommands.swift | 37 ++++++++- Sources/CLI/Terminal.swift | 15 ++++ Tests/CLITests/ManifestExecutableTests.swift | 81 ++++++++++++++++++++ 6 files changed, 152 insertions(+), 53 deletions(-) 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/CHANGELOG.md b/CHANGELOG.md index e1d6fe0..2a4a224 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,8 +26,9 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ### Changed - Project declarations use `.agent/agents.yaml` and user declarations use - `~/.agents/agents.yaml`. Prepare the YAML declaration for an existing scope - before applying changes. Resolved configuration uses the version 2 JSON ledger. + `~/.agents/agents.yaml`. Resolved configuration uses the version 2 JSON ledger. + For an existing user configuration, run `agents manifest migrate` to preview + the upgrade, then repeat with `--apply`. ## [0.2.0] - 2026-10-27 diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 1db688a..d02f833 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -66,6 +66,7 @@ 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 manifest migrate [--apply] 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] @@ -377,6 +378,18 @@ code on stderr; related locations follow when available. Invalid arguments exit 64. See the [dump contract](ManifestDump.md) for encoding and schema ownership. +`manifest migrate` previews a user configuration upgrade from agents 0.2.0. +It reads `~/.agents/agents.json` and its version 1 `agents.resolved` before an +`agents.yaml` exists. The preview lists item counts and the state paths that +will change. It uses retained source content and checks recorded installations +without fetching sources or altering installations. + +Run `agents manifest migrate --apply` to prepare and apply the migration. +It creates `~/.agents/agents.yaml`, writes the version 2 `agents.resolved`, +and saves the exact original ledger bytes in `agents.resolved.original`. +The original declaration and watch state remain available. This command +operates on the user configuration from any working directory. + ## Components Use `agents components inventory > inventory.cdx.json` to export the current project's @@ -926,8 +939,10 @@ 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. +an existing YAML declaration and reports its selected path when absent. Run +`agents manifest migrate` for a user scope that still uses the version 1 lock +and JSON declaration. If a previously migrated declaration is missing, restore +`agents.yaml` before retrying. Project roots are the current directory, not a search up the Git ancestry. Core resolves installation locations, including `CODEX_HOME`, diff --git a/Sources/CLI/ManifestCommands.swift b/Sources/CLI/ManifestCommands.swift index a179dae..5525342 100644 --- a/Sources/CLI/ManifestCommands.swift +++ b/Sources/CLI/ManifestCommands.swift @@ -1,12 +1,45 @@ import AgentsCore import AgentsManifest +import AgentsUpdates import ArgumentParser import Foundation struct Manifest: ParsableCommand { static let configuration = CommandConfiguration( - commandName: "manifest", abstract: "Inspect local declarations.", - subcommands: [DumpManifest.self]) + commandName: "manifest", abstract: "Inspect and migrate local declarations.", + subcommands: [DumpManifest.self, MigrateManifest.self]) +} + +struct MigrateManifest: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "migrate", abstract: "Migrate a user configuration from agents 0.2.0.") + + @Flag(help: "Write the YAML declaration, version 2 ledger, and original ledger backup.") + var apply = false + + func run() throws { + let environment = RuntimeEnvironment() + let paths = HumanPaths(scope: .user, environment: environment) + let preview = try ExistingGlobalConfiguration.preview(environment: environment) + Terminal.write( + """ + User configuration + Source aliases: \(preview.sourceCount) + Locked skills: \(preview.skillCount) + Recorded skill installations: \(preview.installationCount) + Locked instruction sections: \(preview.instructionCount) + Create \(paths.path(preview.declarationURL.path)) + Replace \(paths.path(preview.ledgerURL.path)) + Save the original ledger as \(paths.path(preview.originalLedgerURL.path)) + + """) + if apply { + try ExistingGlobalConfiguration.apply(preview) + Terminal.write("Migrated the user configuration.\n") + } else { + Terminal.write("Preview only. Run again with --apply to migrate.\n") + } + } } struct DumpManifest: ParsableCommand { diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 5a91ec0..4727903 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -93,8 +93,20 @@ enum Terminal { case CoreError.recoveryPending: action = "run 'agents install' in the same scope (add --scope user for user state) to finish recovery" + case CoreError.missingDeclaration(let path) + where path == StateStore(scope: .user).declarationURL.path + && (try? ExistingGlobalConfiguration.isAvailable(environment: RuntimeEnvironment())) == true: + action = "run 'agents manifest migrate' to preview the user configuration migration" case CoreError.missingDeclaration: action = "restore agents.yaml from version control before retrying" + case ExistingGlobalConfigurationError.unavailable: + action = "check that the original user configuration and its version 1 lock are in ~/.agents" + case ExistingGlobalConfigurationError.stalePreview: + action = "run 'agents manifest migrate' for a fresh preview" + case ExistingGlobalConfigurationError.conflict: + action = "resolve the reported configuration conflict before trying again" + case ExistingGlobalConfigurationError.recovery: + action = "follow the recovery directions before trying again" case CoreError.notFound where command is DumpManifest: action = "create agents.yaml in the selected scope before running 'agents manifest dump --json'" @@ -167,6 +179,9 @@ enum Terminal { 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 migration = error as? ExistingGlobalConfigurationError { + return migration.localizedDescription + } if let error = error as? UpdateApplyError { return updateFailureMessage(error.disposition, underlyingError: error.underlyingError) } diff --git a/Tests/CLITests/ManifestExecutableTests.swift b/Tests/CLITests/ManifestExecutableTests.swift index 6bd4980..2a38cb6 100644 --- a/Tests/CLITests/ManifestExecutableTests.swift +++ b/Tests/CLITests/ManifestExecutableTests.swift @@ -4,6 +4,86 @@ import Foundation import Testing struct ManifestExecutableTests { + @Test func migratePreviewsAndConvertsLegacyUserState() throws { + let fixture = try CLIFixture() + let legacyManifest = fixture.state("agents.json", scope: "user") + let ledger = fixture.state("agents.resolved", scope: "user") + let watch = fixture.state("agents.watch", scope: "user") + let yaml = fixture.state("agents.yaml", scope: "user") + let original = fixture.state("agents.resolved.original", scope: "user") + try FileManager.default.createDirectory( + at: fixture.state("", scope: "user"), withIntermediateDirectories: true) + let declarationBytes = Data( + """ + {"agents":["codex"],"sources":{"remote":{"git":"https://example.invalid/repo"}}, + "watch":["remote"]} + """.utf8) + let ledgerBytes = Data( + """ + {"version":1,"sources":{},"skills":{},"instructions":{"sections":[],"targets":{},"chatgpt":{}}} + """.utf8) + let watchBytes = Data(#"{"version":1,"sources":{}}"#.utf8) + try declarationBytes.write(to: legacyManifest) + try ledgerBytes.write(to: ledger) + try watchBytes.write(to: watch) + + let read = try fixture.run(["manifest", "dump", "--scope", "user", "--json"]) + #expect(read.status == 1) + #expect(read.stderr.contains("Run 'agents manifest migrate'")) + + let preview = try fixture.success(["manifest", "migrate"]) + #expect(preview.stdout.contains("Source aliases: 1")) + #expect(preview.stdout.contains("Create ~/.agents/agents.yaml")) + #expect(preview.stdout.contains("Replace ~/.agents/agents.resolved")) + #expect( + preview.stdout.contains("Save the original ledger as ~/.agents/agents.resolved.original")) + #expect(preview.stdout.contains("Run again with --apply")) + #expect( + try Set( + FileManager.default.contentsOfDirectory(atPath: fixture.state("", scope: "user").path)) + == ["agents.json", "agents.resolved", "agents.watch"]) + #expect(try Data(contentsOf: ledger) == ledgerBytes) + + let application = try fixture.success(["manifest", "migrate", "--apply"]) + #expect(application.stdout.hasSuffix("Migrated the user configuration.\n")) + #expect(try Data(contentsOf: legacyManifest) == declarationBytes) + #expect(try Data(contentsOf: watch) == watchBytes) + #expect(try Data(contentsOf: original) == ledgerBytes) + let activeLedger = try Data(contentsOf: ledger) + let decoded = try JSONDecoder().decode(ResolvedLedger.self, from: activeLedger) + #expect(decoded.version == 2) + let activeManifest = try Data(contentsOf: yaml) + #expect( + String(decoding: activeManifest, as: UTF8.self).contains("https://example.invalid/repo")) + try fixture.success(["manifest", "dump", "--scope", "user", "--json"]) + #expect(!FileManager.default.fileExists(atPath: fixture.state("").path)) + + let repeated = try fixture.run(["manifest", "migrate", "--apply"]) + #expect(repeated.status == 1 && repeated.stdout.isEmpty) + #expect(repeated.stderr.contains("requires agents.json and its associated agents.resolved")) + #expect(try Data(contentsOf: yaml) == activeManifest) + #expect(try Data(contentsOf: ledger) == activeLedger) + #expect(try Data(contentsOf: original) == ledgerBytes) + } + + @Test func migrateDoesNotProcessProjectState() throws { + let fixture = try CLIFixture() + let projectJSON = fixture.state("agents.json") + let projectLedger = fixture.state("agents.resolved") + let declarationBytes = Data("{}".utf8) + let ledgerBytes = Data(#"{"version":1}"#.utf8) + try FileManager.default.createDirectory( + at: fixture.state(""), withIntermediateDirectories: true) + try declarationBytes.write(to: projectJSON) + try ledgerBytes.write(to: projectLedger) + let result = try fixture.run(["manifest", "migrate", "--apply"]) + #expect(result.status == 1 && result.stdout.isEmpty) + #expect(try Data(contentsOf: projectJSON) == declarationBytes) + #expect(try Data(contentsOf: projectLedger) == ledgerBytes) + #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.yaml").path)) + #expect(!FileManager.default.fileExists(atPath: fixture.state("", scope: "user").path)) + } + @Test(arguments: ["project", "user"]) func dumpPrintsProducerBytesAndSymbolicValues(_ scope: String) throws { let fixture = try CLIFixture() @@ -126,6 +206,7 @@ struct ManifestExecutableTests { ["manifest", "dump"], ["manifest", "dump", "--scope", "global", "--json"], ["manifest", "dump", "--json", "--path", "other"], ["manifest", "dump", "other", "--json"], ["manifest", "dump", "--json", "--apply"], ["manifest", "unknown", "--help"], + ["manifest", "migrate", "--scope", "project"], ]) func usageErrors(_ arguments: [String]) throws { let fixture = try CLIFixture() From 436180dccc1272e45bc6fd753e8668f853923113 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 03:58:15 +0800 Subject: [PATCH 62/67] fix: use bounded subprocess cleanup on cancellation --- Package.resolved | 4 ++-- Package.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Package.resolved b/Package.resolved index 8d0abbf..ac0342f 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "39a863192c469042cbf99a8c03effcdfd3a35834c982c257b2159cb584dd50d3", + "originHash" : "ba9a510d9756d11c4fd9e1cc7446a2e7c92d976cdf96896fcb83ba1314c138d3", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "d3649defa0539ef339fba14b52f3e9d24619f776" + "revision" : "7cb9385303848981f0dab79b446e18bd407dbabd" } }, { diff --git a/Package.swift b/Package.swift index 2658f8d..fdc0777 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "d3649defa0539ef339fba14b52f3e9d24619f776"), + revision: "7cb9385303848981f0dab79b446e18bd407dbabd"), ], targets: [ .executableTarget( From a46f60e63a63a71b78985f18aa8eb80662e9f870 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:30:02 +0800 Subject: [PATCH 63/67] fix: use the current configuration format directly --- CHANGELOG.md | 2 - Documentation/Reference/CLI.md | 19 +---- Sources/CLI/ManifestCommands.swift | 37 +-------- Sources/CLI/Terminal.swift | 15 ---- Tests/CLITests/ManifestExecutableTests.swift | 81 -------------------- 5 files changed, 4 insertions(+), 150 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a4a224..6a5a93b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,8 +27,6 @@ publication follows the [release checklist](Documentation/Reference/Release.md). - Project declarations use `.agent/agents.yaml` and user declarations use `~/.agents/agents.yaml`. Resolved configuration uses the version 2 JSON ledger. - For an existing user configuration, run `agents manifest migrate` to preview - the upgrade, then repeat with `--apply`. ## [0.2.0] - 2026-10-27 diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index d02f833..1db688a 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -66,7 +66,6 @@ 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 manifest migrate [--apply] 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] @@ -378,18 +377,6 @@ code on stderr; related locations follow when available. Invalid arguments exit 64. See the [dump contract](ManifestDump.md) for encoding and schema ownership. -`manifest migrate` previews a user configuration upgrade from agents 0.2.0. -It reads `~/.agents/agents.json` and its version 1 `agents.resolved` before an -`agents.yaml` exists. The preview lists item counts and the state paths that -will change. It uses retained source content and checks recorded installations -without fetching sources or altering installations. - -Run `agents manifest migrate --apply` to prepare and apply the migration. -It creates `~/.agents/agents.yaml`, writes the version 2 `agents.resolved`, -and saves the exact original ledger bytes in `agents.resolved.original`. -The original declaration and watch state remain available. This command -operates on the user configuration from any working directory. - ## Components Use `agents components inventory > inventory.cdx.json` to export the current project's @@ -939,10 +926,8 @@ 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 YAML declaration and reports its selected path when absent. Run -`agents manifest migrate` for a user scope that still uses the version 1 lock -and JSON declaration. If a previously migrated declaration is missing, restore -`agents.yaml` before retrying. +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`, diff --git a/Sources/CLI/ManifestCommands.swift b/Sources/CLI/ManifestCommands.swift index 5525342..a179dae 100644 --- a/Sources/CLI/ManifestCommands.swift +++ b/Sources/CLI/ManifestCommands.swift @@ -1,45 +1,12 @@ import AgentsCore import AgentsManifest -import AgentsUpdates import ArgumentParser import Foundation struct Manifest: ParsableCommand { static let configuration = CommandConfiguration( - commandName: "manifest", abstract: "Inspect and migrate local declarations.", - subcommands: [DumpManifest.self, MigrateManifest.self]) -} - -struct MigrateManifest: ParsableCommand { - static let configuration = CommandConfiguration( - commandName: "migrate", abstract: "Migrate a user configuration from agents 0.2.0.") - - @Flag(help: "Write the YAML declaration, version 2 ledger, and original ledger backup.") - var apply = false - - func run() throws { - let environment = RuntimeEnvironment() - let paths = HumanPaths(scope: .user, environment: environment) - let preview = try ExistingGlobalConfiguration.preview(environment: environment) - Terminal.write( - """ - User configuration - Source aliases: \(preview.sourceCount) - Locked skills: \(preview.skillCount) - Recorded skill installations: \(preview.installationCount) - Locked instruction sections: \(preview.instructionCount) - Create \(paths.path(preview.declarationURL.path)) - Replace \(paths.path(preview.ledgerURL.path)) - Save the original ledger as \(paths.path(preview.originalLedgerURL.path)) - - """) - if apply { - try ExistingGlobalConfiguration.apply(preview) - Terminal.write("Migrated the user configuration.\n") - } else { - Terminal.write("Preview only. Run again with --apply to migrate.\n") - } - } + commandName: "manifest", abstract: "Inspect local declarations.", + subcommands: [DumpManifest.self]) } struct DumpManifest: ParsableCommand { diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 4727903..5a91ec0 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -93,20 +93,8 @@ enum Terminal { case CoreError.recoveryPending: action = "run 'agents install' in the same scope (add --scope user for user state) to finish recovery" - case CoreError.missingDeclaration(let path) - where path == StateStore(scope: .user).declarationURL.path - && (try? ExistingGlobalConfiguration.isAvailable(environment: RuntimeEnvironment())) == true: - action = "run 'agents manifest migrate' to preview the user configuration migration" case CoreError.missingDeclaration: action = "restore agents.yaml from version control before retrying" - case ExistingGlobalConfigurationError.unavailable: - action = "check that the original user configuration and its version 1 lock are in ~/.agents" - case ExistingGlobalConfigurationError.stalePreview: - action = "run 'agents manifest migrate' for a fresh preview" - case ExistingGlobalConfigurationError.conflict: - action = "resolve the reported configuration conflict before trying again" - case ExistingGlobalConfigurationError.recovery: - action = "follow the recovery directions before trying again" case CoreError.notFound where command is DumpManifest: action = "create agents.yaml in the selected scope before running 'agents manifest dump --json'" @@ -179,9 +167,6 @@ enum Terminal { 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 migration = error as? ExistingGlobalConfigurationError { - return migration.localizedDescription - } if let error = error as? UpdateApplyError { return updateFailureMessage(error.disposition, underlyingError: error.underlyingError) } diff --git a/Tests/CLITests/ManifestExecutableTests.swift b/Tests/CLITests/ManifestExecutableTests.swift index 2a38cb6..6bd4980 100644 --- a/Tests/CLITests/ManifestExecutableTests.swift +++ b/Tests/CLITests/ManifestExecutableTests.swift @@ -4,86 +4,6 @@ import Foundation import Testing struct ManifestExecutableTests { - @Test func migratePreviewsAndConvertsLegacyUserState() throws { - let fixture = try CLIFixture() - let legacyManifest = fixture.state("agents.json", scope: "user") - let ledger = fixture.state("agents.resolved", scope: "user") - let watch = fixture.state("agents.watch", scope: "user") - let yaml = fixture.state("agents.yaml", scope: "user") - let original = fixture.state("agents.resolved.original", scope: "user") - try FileManager.default.createDirectory( - at: fixture.state("", scope: "user"), withIntermediateDirectories: true) - let declarationBytes = Data( - """ - {"agents":["codex"],"sources":{"remote":{"git":"https://example.invalid/repo"}}, - "watch":["remote"]} - """.utf8) - let ledgerBytes = Data( - """ - {"version":1,"sources":{},"skills":{},"instructions":{"sections":[],"targets":{},"chatgpt":{}}} - """.utf8) - let watchBytes = Data(#"{"version":1,"sources":{}}"#.utf8) - try declarationBytes.write(to: legacyManifest) - try ledgerBytes.write(to: ledger) - try watchBytes.write(to: watch) - - let read = try fixture.run(["manifest", "dump", "--scope", "user", "--json"]) - #expect(read.status == 1) - #expect(read.stderr.contains("Run 'agents manifest migrate'")) - - let preview = try fixture.success(["manifest", "migrate"]) - #expect(preview.stdout.contains("Source aliases: 1")) - #expect(preview.stdout.contains("Create ~/.agents/agents.yaml")) - #expect(preview.stdout.contains("Replace ~/.agents/agents.resolved")) - #expect( - preview.stdout.contains("Save the original ledger as ~/.agents/agents.resolved.original")) - #expect(preview.stdout.contains("Run again with --apply")) - #expect( - try Set( - FileManager.default.contentsOfDirectory(atPath: fixture.state("", scope: "user").path)) - == ["agents.json", "agents.resolved", "agents.watch"]) - #expect(try Data(contentsOf: ledger) == ledgerBytes) - - let application = try fixture.success(["manifest", "migrate", "--apply"]) - #expect(application.stdout.hasSuffix("Migrated the user configuration.\n")) - #expect(try Data(contentsOf: legacyManifest) == declarationBytes) - #expect(try Data(contentsOf: watch) == watchBytes) - #expect(try Data(contentsOf: original) == ledgerBytes) - let activeLedger = try Data(contentsOf: ledger) - let decoded = try JSONDecoder().decode(ResolvedLedger.self, from: activeLedger) - #expect(decoded.version == 2) - let activeManifest = try Data(contentsOf: yaml) - #expect( - String(decoding: activeManifest, as: UTF8.self).contains("https://example.invalid/repo")) - try fixture.success(["manifest", "dump", "--scope", "user", "--json"]) - #expect(!FileManager.default.fileExists(atPath: fixture.state("").path)) - - let repeated = try fixture.run(["manifest", "migrate", "--apply"]) - #expect(repeated.status == 1 && repeated.stdout.isEmpty) - #expect(repeated.stderr.contains("requires agents.json and its associated agents.resolved")) - #expect(try Data(contentsOf: yaml) == activeManifest) - #expect(try Data(contentsOf: ledger) == activeLedger) - #expect(try Data(contentsOf: original) == ledgerBytes) - } - - @Test func migrateDoesNotProcessProjectState() throws { - let fixture = try CLIFixture() - let projectJSON = fixture.state("agents.json") - let projectLedger = fixture.state("agents.resolved") - let declarationBytes = Data("{}".utf8) - let ledgerBytes = Data(#"{"version":1}"#.utf8) - try FileManager.default.createDirectory( - at: fixture.state(""), withIntermediateDirectories: true) - try declarationBytes.write(to: projectJSON) - try ledgerBytes.write(to: projectLedger) - let result = try fixture.run(["manifest", "migrate", "--apply"]) - #expect(result.status == 1 && result.stdout.isEmpty) - #expect(try Data(contentsOf: projectJSON) == declarationBytes) - #expect(try Data(contentsOf: projectLedger) == ledgerBytes) - #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.yaml").path)) - #expect(!FileManager.default.fileExists(atPath: fixture.state("", scope: "user").path)) - } - @Test(arguments: ["project", "user"]) func dumpPrintsProducerBytesAndSymbolicValues(_ scope: String) throws { let fixture = try CLIFixture() @@ -206,7 +126,6 @@ struct ManifestExecutableTests { ["manifest", "dump"], ["manifest", "dump", "--scope", "global", "--json"], ["manifest", "dump", "--json", "--path", "other"], ["manifest", "dump", "other", "--json"], ["manifest", "dump", "--json", "--apply"], ["manifest", "unknown", "--help"], - ["manifest", "migrate", "--scope", "project"], ]) func usageErrors(_ arguments: [String]) throws { let fixture = try CLIFixture() From 0782b067fd4d0b809cbf034377cd8a63a5b72e6d Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:38:21 +0800 Subject: [PATCH 64/67] build: select the Core release candidate --- Package.resolved | 4 ++-- Package.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Package.resolved b/Package.resolved index ac0342f..3af06e6 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "ba9a510d9756d11c4fd9e1cc7446a2e7c92d976cdf96896fcb83ba1314c138d3", + "originHash" : "7c497002f1ceb1c26535caad5db742e6e9e35f2ded6c971d87562ee65166c189", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "7cb9385303848981f0dab79b446e18bd407dbabd" + "revision" : "5de4d60fcbfa65a2c3b85c5c4642b335eea898ed" } }, { diff --git a/Package.swift b/Package.swift index fdc0777..61c31ad 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "7cb9385303848981f0dab79b446e18bd407dbabd"), + revision: "5de4d60fcbfa65a2c3b85c5c4642b335eea898ed"), ], targets: [ .executableTarget( From fda9591f60e3b022de3117665c2ebf5fea4293ef Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:49:01 +0800 Subject: [PATCH 65/67] chore: prepare CLI 0.3.1 --- CHANGELOG.md | 2 +- Sources/CLI/EntryPoint.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a5a93b..475c222 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,7 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased -## [0.3.0] - 2026-11-29 +## [0.3.1] - 2026-11-29 ### Added diff --git a/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index 257d69b..ec080be 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -9,7 +9,7 @@ import Foundation #endif enum BuildInfo { - static let version = "0.3.0" + static let version = "0.3.1" } struct Agents: ParsableCommand { From 6d4781816de3c8dc1b31e12c36b0f785a2282364 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 12:55:28 +0800 Subject: [PATCH 66/67] build: select the current Core configuration API --- Package.resolved | 4 ++-- Package.swift | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Package.resolved b/Package.resolved index 3af06e6..99b8e39 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,12 @@ { - "originHash" : "7c497002f1ceb1c26535caad5db742e6e9e35f2ded6c971d87562ee65166c189", + "originHash" : "263146f669a4d5bdec3794ab041aa130c1391637d013169135d3eca7c924e585", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "5de4d60fcbfa65a2c3b85c5c4642b335eea898ed" + "revision" : "a2b665cbd4ad07aa8df0e191742f53855d699940" } }, { diff --git a/Package.swift b/Package.swift index 61c31ad..cbcab3a 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "5de4d60fcbfa65a2c3b85c5c4642b335eea898ed"), + revision: "a2b665cbd4ad07aa8df0e191742f53855d699940"), ], targets: [ .executableTarget( From fc06402d220bbc661254d66d511a49bceb1ba636 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Sun, 29 Nov 2026 16:29:32 +0800 Subject: [PATCH 67/67] build: require the published Core 0.3.1 release --- Package.resolved | 5 +++-- Package.swift | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Package.resolved b/Package.resolved index 99b8e39..c4214d4 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,12 +1,13 @@ { - "originHash" : "263146f669a4d5bdec3794ab041aa130c1391637d013169135d3eca7c924e585", + "originHash" : "8da077cf245d6fbebc8831b63b38cc6354f159c9999e2a161197b12048635975", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "a2b665cbd4ad07aa8df0e191742f53855d699940" + "revision" : "ce6640adeb53ce0152134547938a6e13472e28b5", + "version" : "0.3.1" } }, { diff --git a/Package.swift b/Package.swift index cbcab3a..81edb7d 100644 --- a/Package.swift +++ b/Package.swift @@ -10,7 +10,7 @@ let package = Package( .package(url: "https://github.com/apple/swift-argument-parser", from: "1.7.0"), .package( url: "https://github.com/agents-tools/core.git", - revision: "a2b665cbd4ad07aa8df0e191742f53855d699940"), + "0.3.1"..<"0.4.0"), ], targets: [ .executableTarget(