diff --git a/.agent/agents.json b/.agent/agents.json new file mode 100644 index 0000000..5c68742 --- /dev/null +++ b/.agent/agents.json @@ -0,0 +1,17 @@ +{ + "instructions": { + "agents": ["claude-code", "codex"], + "sections": [ + "guide", + "agents-tools:shared/swift-package-route", + "agents-tools:shared/swift-package-tests" + ] + }, + "sources": { + "agents-tools": { + "branch": "master", + "git": "github.com/agents-tools/.github", + "path": ".agent" + } + } +} diff --git a/.agent/agents.resolved b/.agent/agents.resolved new file mode 100644 index 0000000..3fd02bf --- /dev/null +++ b/.agent/agents.resolved @@ -0,0 +1,47 @@ +{ + "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 +} diff --git a/.agent/instructions/guide.md b/.agent/instructions/guide.md new file mode 100644 index 0000000..f9e1078 --- /dev/null +++ b/.agent/instructions/guide.md @@ -0,0 +1,23 @@ +--- +description: Keep the agents CLI a command layer over core, with its own schemas, contract document and verified CI contexts. +--- +# cli Agent Guide + +## Ownership + +- Keep command parsing, terminal output, exit codes and JSON schemas here, and + keep CLI schema types independent of core's encoded representations. +- Keep source resolution, declarations, locks, recovery, discovery and skill + lifecycle behavior in agents-tools/core; use its public APIs. +- Update `Documentation/Reference/CLI.md`, the shipped command contract, with + every command change. The executable version lives in + `Sources/CLI/EntryPoint.swift`. + +## Workflows and Assets + +- For workflow changes, run `actionlint` on every workflow. Verify the required + checks on a real candidate run before changing required-check settings. +- The demo job re-records `recording.json` and uploads it on drift. Render and + check terminal SVGs and the social preview locally with the + github-readme-design toolchain against `agents-tools/.github`'s DESIGN, fonts + and catalog. diff --git a/.github/assets/terminal/recording.json b/.github/assets/terminal/recording.json index 924ea8d..88fee33 100644 --- a/.github/assets/terminal/recording.json +++ b/.github/assets/terminal/recording.json @@ -11,7 +11,7 @@ }, { "command": "agents watch add ~/team-rules", - "output": "Watching local:~/team-rules from f4042e6." + "output": "Watching local:~/team-rules from 6fd753f." }, { "command": "git -C ~/team-rules commit -qam \"docs: review tests\"", @@ -19,11 +19,11 @@ }, { "command": "agents watch", - "output": "local:~/team-rules 1 commit since f4042e6 (now e21e12f)\n ~ changed code-review (instructions) 1 file" + "output": "local:~/team-rules 1 commit since 6fd753f (now da238b5)\n ~ changed code-review (instructions) 1 file" }, { "command": "agents update --apply", - "output": "~ changed code-review (instructions) local:~/team-rules f4042e6 -> e21e12f\n= repinned commits (instructions) local:~/team-rules f4042e6 -> e21e12f\n= repinned pdf local:~/team-rules f4042e6 -> e21e12f\n = unchanged claude-code (link) .claude/skills/pdf\n = unchanged codex (link) .agents/skills/pdf\nAGENTS.md (claude-code, codex)\n--- a/AGENTS.md\n+++ b/AGENTS.md\n@@ -2,7 +2,7 @@\n # Code review\n \n Check correctness.\n-Review code.\n+Review code and tests.\n \n # Commits\n \nUpdated pdf for claude-code, codex: f4042e6 -> e21e12f.\nUpdated AGENTS.md." + "output": "~ changed code-review (instructions) local:~/team-rules 6fd753f -> da238b5\n= repinned commits (instructions) local:~/team-rules 6fd753f -> da238b5\n= repinned pdf local:~/team-rules 6fd753f -> da238b5\n = unchanged claude-code (link) .claude/skills/pdf\n = unchanged codex (link) .agents/skills/pdf\nAGENTS.md (claude-code, codex)\n--- a/AGENTS.md\n+++ b/AGENTS.md\n@@ -3,7 +3,7 @@\n # Code review\n \n Check correctness.\n-Review code.\n+Review code and tests.\n \n # Commits\n \nUpdated pdf for claude-code, codex: 6fd753f -> da238b5.\nUpdated AGENTS.md." } ] } diff --git a/.github/assets/terminal/script.yml b/.github/assets/terminal/script.yml index cab6d4c..3a35caf 100644 --- a/.github/assets/terminal/script.yml +++ b/.github/assets/terminal/script.yml @@ -9,11 +9,17 @@ files: Inspect page sizes, annotations, and extracted text. team-rules/instructions/code-review.md: | + --- + description: Review checklist. + --- # Code review Check correctness. Review code. team-rules/instructions/commits.md: | + --- + description: Commit message rules. + --- # Commits Use clear messages. @@ -26,6 +32,9 @@ steps: - run: agents watch add ~/team-rules - write: ~/team-rules/instructions/code-review.md content: | + --- + description: Review checklist. + --- # Code review Check correctness. diff --git a/.github/assets/terminal/terminal-dark.svg b/.github/assets/terminal/terminal-dark.svg index 2ce7326..03c5ee4 100644 --- a/.github/assets/terminal/terminal-dark.svg +++ b/.github/assets/terminal/terminal-dark.svg @@ -7,24 +7,24 @@ $ agents instructions add ~/team-rules code-review commits Added code-review, commits to AGENTS.md (claude-code, codex). $ agents watch add ~/team-rules -Watching local:~/team-rules from f4042e6. +Watching local:~/team-rules from 6fd753f. $ git -C ~/team-rules commit -qam "docs: review tests" $ agents watch -local:~/team-rules 1 commit since f4042e6 (now e21e12f) +local:~/team-rules 1 commit since 6fd753f (now da238b5) ~ changed code-review (instructions) 1 file $ agents update --apply -~ changed code-review (instructions) local:~/team-rules f4042e6 -> e21e12f -= repinned commits (instructions) local:~/team-rules f4042e6 -> e21e12f -= repinned pdf local:~/team-rules f4042e6 -> e21e12f +~ changed code-review (instructions) local:~/team-rules 6fd753f -> da238b5 += repinned commits (instructions) local:~/team-rules 6fd753f -> da238b5 += repinned pdf local:~/team-rules 6fd753f -> da238b5 = unchanged claude-code (link) .claude/skills/pdf = unchanged codex (link) .agents/skills/pdf AGENTS.md (claude-code, codex) --- a/AGENTS.md +++ b/AGENTS.md -@@ -2,7 +2,7 @@ +@@ -3,7 +3,7 @@ # Code review Check correctness. @@ -33,7 +33,7 @@ AGENTS.md (claude-code, codex) # Commits -Updated pdf for claude-code, codex: f4042e6 -> e21e12f. +Updated pdf for claude-code, codex: 6fd753f -> da238b5. Updated AGENTS.md. @@ -45,12 +45,13 @@ Updated AGENTS.md. - - + + + @@ -106,24 +107,24 @@ Updated AGENTS.md. - + - + - - - + + + - + @@ -132,6 +133,6 @@ Updated AGENTS.md. - + diff --git a/.github/assets/terminal/terminal-light.svg b/.github/assets/terminal/terminal-light.svg index f89df54..6c8d7a4 100644 --- a/.github/assets/terminal/terminal-light.svg +++ b/.github/assets/terminal/terminal-light.svg @@ -7,24 +7,24 @@ $ agents instructions add ~/team-rules code-review commits Added code-review, commits to AGENTS.md (claude-code, codex). $ agents watch add ~/team-rules -Watching local:~/team-rules from f4042e6. +Watching local:~/team-rules from 6fd753f. $ git -C ~/team-rules commit -qam "docs: review tests" $ agents watch -local:~/team-rules 1 commit since f4042e6 (now e21e12f) +local:~/team-rules 1 commit since 6fd753f (now da238b5) ~ changed code-review (instructions) 1 file $ agents update --apply -~ changed code-review (instructions) local:~/team-rules f4042e6 -> e21e12f -= repinned commits (instructions) local:~/team-rules f4042e6 -> e21e12f -= repinned pdf local:~/team-rules f4042e6 -> e21e12f +~ changed code-review (instructions) local:~/team-rules 6fd753f -> da238b5 += repinned commits (instructions) local:~/team-rules 6fd753f -> da238b5 += repinned pdf local:~/team-rules 6fd753f -> da238b5 = unchanged claude-code (link) .claude/skills/pdf = unchanged codex (link) .agents/skills/pdf AGENTS.md (claude-code, codex) --- a/AGENTS.md +++ b/AGENTS.md -@@ -2,7 +2,7 @@ +@@ -3,7 +3,7 @@ # Code review Check correctness. @@ -33,7 +33,7 @@ AGENTS.md (claude-code, codex) # Commits -Updated pdf for claude-code, codex: f4042e6 -> e21e12f. +Updated pdf for claude-code, codex: 6fd753f -> da238b5. Updated AGENTS.md. @@ -45,12 +45,13 @@ Updated AGENTS.md. - - + + + @@ -106,24 +107,24 @@ Updated AGENTS.md. - + - + - - - + + + - + @@ -132,6 +133,6 @@ Updated AGENTS.md. - + diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 48bfaeb..7907540 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@3fb2887e2831d9d5a287af73819e2ba3a39d0045 + uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@bb0a8c8c39827a364b9d3cbf4069754e7d975586 diff --git a/.github/workflows/source-policy.yml b/.github/workflows/source-policy.yml index d58f828..b6a1735 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@3fb2887e2831d9d5a287af73819e2ba3a39d0045 + uses: agents-tools/github-workflows/.github/workflows/policy.yml@bb0a8c8c39827a364b9d3cbf4069754e7d975586 with: allow-terms: | ChatGPT diff --git a/.gitignore b/.gitignore index 6b200c6..a2e2dbd 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,7 @@ .swiftpm/ .DS_Store .claude/ -.agent/ +/.agent/* +!/.agent/instructions/ +!/.agent/agents.json +!/.agent/agents.resolved diff --git a/AGENTS.md b/AGENTS.md index 7f603af..c733946 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,40 +1,45 @@ -# cli Agent Guide + -Read `README.md` for purpose, usage, and development commands, then -`Documentation/README.md` for documentation placement. +# cli Agent Guide ## Ownership -- Keep command parsing, terminal output, exit codes, and JSON schemas here. -- Keep source resolution, declarations, locks, recovery, discovery, and skill - lifecycle behavior in `agents-tools/core`. Use its public APIs. -- `Documentation/Reference/CLI.md` describes the shipped command contract. -- `Package.swift` owns the package graph; `Package.resolved` pins development - dependencies; `Sources/CLI/EntryPoint.swift` owns the executable version. - -## Working Conventions - -- Follow the organization's - [maintenance change flow](https://github.com/agents-tools/.github/blob/master/MAINTENANCE.md#change-flow) - and use the repository's local signing configuration. Push and merge require - the user's authorization. -- Do not embed machine-specific paths or execution state in reusable files. -- Keep CLI schema types independent of core's encoded representations. -- Use Swift tools 6.3 and a macOS 15 deployment floor. Shared CI compiles and - tests only with Xcode 26.6 on `macos-26`. -- Run executable tests with an isolated HOME and an allowlisted environment. - Never inherit agent configuration, XDG variables, or Git configuration. - Create Git fixtures with an explicit initial branch and remove all fixtures. -- Keep temporary task reports in ignored `.agent/`; SwiftPM owns `.build/`. -- Run the build, test, release build, and strict format lint checks from the - README before handing off behavior changes. -- For workflow changes, run `actionlint` on every workflow. Keep shared callers - pinned to the same full commit in `agents-tools/github-workflows` and configure - package validation in `.github/swift-package.json`. Behavior assertions belong - in the package tests. -- Required checks are exactly `policy / policy` and `validate / result`. Verify - them on a real candidate run before changing required-check settings. +- Keep command parsing, terminal output, exit codes and JSON schemas here, and + keep CLI schema types independent of core's encoded representations. +- Keep source resolution, declarations, locks, recovery, discovery and skill + lifecycle behavior in agents-tools/core; use its public APIs. +- Update `Documentation/Reference/CLI.md`, the shipped command contract, with + every command change. The executable version lives in + `Sources/CLI/EntryPoint.swift`. + +## Workflows and Assets + +- For workflow changes, run `actionlint` on every workflow. Verify the required + checks on a real candidate run before changing required-check settings. - The demo job re-records `recording.json` and uploads it on drift. Render and check terminal SVGs and the social preview locally with the github-readme-design toolchain against `agents-tools/.github`'s DESIGN, fonts - and catalog, following `Documentation/Reference/TerminalDemo.md`. + and catalog. + +## Package Route + +- Read `README.md` and, when present, `CONTRIBUTING.md` before editing, and + follow the organization + [maintenance change flow](https://github.com/agents-tools/.github/blob/master/MAINTENANCE.md#change-flow). +- Before changing versions, dependencies, packaging or release workflows, read + the organization [VERSIONING](https://github.com/agents-tools/.github/blob/master/VERSIONING.md) + and `Documentation/Reference/Release.md`. +- `.github/swift-package.json` configures package validation; the required + checks are `policy / policy` and `validate / result`. Keep shared workflow + callers pinned to one full commit of agents-tools/github-workflows. +- Read toolchain and deployment minimums from `Package.swift` and + `.github/swift-package.json` instead of restating them. +- Read `Documentation/README.md` before placing documentation and + `Documentation/Architecture/README.md` before changing package structure. + +## Test Isolation + +- Run tests with an isolated `HOME` and with `CODEX_HOME`, `CLAUDE_CONFIG_DIR` + and the `XDG_*` variables unset; never inherit agent or Git configuration. +- Create Git fixtures with an explicit initial branch, and remove every + fixture and temporary directory a test creates. diff --git a/CHANGELOG.md b/CHANGELOG.md index 11f9fff..3401fdb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,43 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## [0.2.0] - 2026-10-27 + +Built on agents-tools/core 0.2.0. + +### Added + +- `agents instructions add . ` and `agents instructions list .` use the + project's own instructions in `.agent/instructions/`. +- `agents instructions export [--root …] [--json]` maps the locked targets + of the user scope and each project to their sections, without writing. +- `agents instructions update --apply --replace` takes over target files that + agents did not generate. +- Instruction source listings show each file's heading level, description and + `paths`. + +### Changed + +- **Breaking:** instruction targets are generated in full from instructions + files with front matter; custom content around managed blocks and conflict + adoption are gone. `--replace` on `instructions add` now takes over files + that agents did not generate, after printing + `Take over , which agents did not generate` and the diff. A file that + agents did not generate also stops `install` and `remove`. Removal names an + edited target it leaves in place, and `add` names the sections each target + received. +- `agents.json` and `agents.resolved` are written in Prettier's default JSON + layout; `agents instructions update --apply` rewrites files in the earlier + layout even when their content is unchanged. +- **Breaking:** `agents instructions init ` creates + `.agent/instructions/.md` in the current project, with front matter. +- **Breaking:** update, instruction update and install JSON reports use + `schemaVersion: 2`. Instruction targets drop `adoptedSections` and + `conflicts`, add `foreign`, and report `drift` as `clean`, `drifted` or + `missing`. Doctor's `foreignTarget` and `invalidLink` diagnostics are + errors, and `conflict` is gone. +- `instructions list --json` no longer reports target `headingOffset`. + ## [0.1.2] - 2026-10-25 Built on agents-tools/core 0.1.2. diff --git a/Documentation/Reference/CLI.md b/Documentation/Reference/CLI.md index 7625b13..fb7dadf 100644 --- a/Documentation/Reference/CLI.md +++ b/Documentation/Reference/CLI.md @@ -12,11 +12,12 @@ agents skills list [source] [--json] agents skills remove agents skills update [names…] [--apply | --json] agents skills init [name] -agents instructions add [names…] [--replace] -agents instructions list [source] [--json] +agents instructions add [names…] [--replace] +agents instructions list [source|.] [--json] agents instructions remove -agents instructions update [--apply | --json] +agents instructions update [--apply [--replace] | --json] agents instructions render chatgpt +agents instructions export [--root …] [--json] agents instructions init agents watch agents watch add [--path ] [requirement options] [--scope project|user] @@ -54,15 +55,16 @@ Examples: | Option | Meaning | Commands | | --- | --- | --- | -| `--scope project\|user` | Where state lives: project (./.agent) or user (~/.agents). Default: project. | All lifecycle and read commands; `init` uses the current directory | +| `--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` | | `--path ` | Search this subdirectory of the source. | Both kinds' `add` and `list `, `watch add` | | `--full-depth` | Discover recursively beyond conventional skill directories | `skills add`, `skills list ` | | `--mode link\|copy\|edit` | How to install: link (default), copy, or edit (a live link to a local source). | `skills add` | -| `--root …` | Audit these project directories read-only. Repeat for several. | `doctor` | -| `--json` | Emit a versioned JSON report on stdout | Both kinds' `list`, `install`, `doctor`, all update previews, `watch status`, `watch diff` | +| `--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` | Agents are `codex`, `claude-code`, `cursor`, `gemini-cli`, and `opencode`. For instruction recipients, Cursor supports project scope only. ChatGPT is a @@ -153,35 +155,58 @@ identifiers; use the source ID and skill name for identity. ## Instructions Instruction sources are Git URLs, shorthands, local Git roots, or existing -source aliases. Discovery reads committed `*.md` files directly inside -`instructions/` and `.agents/instructions/`, relative to the source root or -`--path` subdirectory. Local paths must identify the Git root. Instruction add -supports the same requirement options as skill add; instructions do not have -installation modes, recursive discovery, or `--all`. +source aliases. Discovery reads committed `*.md` files, including those in +subdirectories, inside `instructions/` and `.agents/instructions/`, relative to +the source root or `--path` subdirectory. A file's name is its +container-relative path without `.md`, such as `epd/review`. Local paths must +identify the Git root. Instruction add supports the same requirement options as +skill add; instructions do not have installation modes or `--all`. The source +`.` is the project's own `.agent/instructions/`: its files are read from the +working tree, referenced by bare name, and locked by hash. + +Each instructions file starts with front matter holding a required +`description` and optional `paths`, a list of glob patterns using `*`, `**` +and `?`. The body starts with one heading at any level, and every other heading +in it is deeper. `instructions init ` creates +`.agent/instructions/.md` with this skeleton in the current project and +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; -`instructions list` reports locked sections, physical targets and named prompts, -including missing targets. Doctor reports their disk status. - -Core writes one managed block per physical target and preserves custom content -around it. The block and its adjacent separating blank lines belong to core; -removing the block also removes those separators. 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. Headings shift below an existing title. -When a project Claude file exists, core adds a managed import of `AGENTS.md` -where needed. Existing forwarding and custom content are preserved. - -Conflicting custom sections stop add with differences in the diagnostic. -`--replace` displays a unified target diff before replacing conflicts. -`instructions remove ` removes sections from file targets and ChatGPT -prompts. Use `source-alias:name` if a bare name is ambiguous. Empty managed -blocks are removed; files created by core are deleted only when no custom -content remains. `instructions init ` creates `.md` in the current -directory and rejects an existing file. +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 +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 +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 +`install` and `remove`, move the file aside and retry, then put what it needs +into instructions files. `instructions remove ` removes sections from file targets and +ChatGPT prompts. Use `source-alias:name` if a bare name is ambiguous. A target +left without sections is deleted while it matches its locked rendering; an +edited one stays in place and leaves the lock. + +`instructions export [--root …]` maps each locked target to the sections +it receives, reading the user scope and then each project root (default: the +current directory) without writing. A scope without a lock, with pending +recovery, or with unreadable state is reported with that status. A project +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 source alias (here `rules`): @@ -465,13 +490,17 @@ Removed commits from AGENTS.md. Removed pdf for claude-code, codex. ``` -Normal instruction adds print only the completion lines. Replacing conflicting -custom sections with `--replace` prints the conflict diff first. Instruction -removal prints target diffs before its completion lines. +Normal instruction adds print only the completion lines. Taking over a file +with `--replace` first prints `Take over , which agents did not generate` +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, -hashes, modes, recipients, and heading offsets. It does not resolve newer versions and takes no source argument. Unavailable pins or content -that fails digest verification cause failure. +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. `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` @@ -496,9 +525,11 @@ Concurrent external edits can invalidate a preparation and remain untouched. Doctor reports skills first, then instructions for each root. Skill checks include missing installations, drift, broken links, newer matching source revisions, and uncommitted source content. Instruction checks include missing -or drifted blocks, adoption/conflicts, missing locks, sections at both scopes, -Claude forwarding and ancestor files, Codex override files and size limits, -source changes, and invalid configuration. `--root` audits both kinds. +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. `--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 @@ -509,6 +540,14 @@ current directory and user scope uses HOME. | 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 roots are the current directory, not a search up the Git ancestry. Core resolves installation locations, including `CODEX_HOME`, `CLAUDE_CONFIG_DIR`, and `XDG_CONFIG_HOME` when applicable. User state remains @@ -585,16 +624,17 @@ 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`, `conflict`, `invalidConfiguration`, and +Instruction `invalidTarget`, `foreignTarget`, `invalidLink`, `invalidConfiguration`, and `stateUnavailable` diagnostics and both pending-recovery findings are errors. -Other instruction diagnostics, including drift and missing blocks, are +Other instruction diagnostics, including drift and missing targets, are warnings. Other skill severities are supplied by core. A failed operation emits no successful JSON report. JSON stdout contains only one object and a trailing newline; recovery notices remain on stderr. ## JSON Schemas -All reports have integer `schemaVersion: 1`. Object keys are sorted. Arrays +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 selection order, targets and prompt names are sorted, and doctor roots retain input order. @@ -619,6 +659,7 @@ schema version. Diagnostic IDs are core-defined strings, not a closed enum. | `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` | @@ -633,7 +674,7 @@ An empty installed list: An empty skill update preview: ```json -{"schemaVersion":1,"scope":"project","changed":false,"skills":[]} +{"schemaVersion":2,"scope":"project","changed":false,"skills":[]} ``` A healthy doctor report: @@ -650,9 +691,8 @@ physical `path`, `before` and `after`. Membership states use `{"kind":"absent"}` or `{"kind":"installed","mode":"link|copy|edit"}`. 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 additive -fields retain schema version 1 and are optional in the schema so older reports -remain valid. +`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 remain, and instruction IDs use core's diagnostic names. Consumers distinguish checks by `(kind, id)` because kinds may use the same ID. @@ -664,9 +704,10 @@ The shared [instruction definitions](Schemas/instructions.schema.json) describe: `changed` (file bytes differ), `agentsChanged` (recipients differ), `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`, `adoptedSections`, and - `conflicts` with existing/proposed text and difference. Agent IDs use their - raw values in deterministic order. + `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 + deterministic order. - `changedPrompts`: prompt names whose content definition changed. - `lockMissing`: no scope lock existed when the operation began. - `changed`: applying changes the declaration, locked state, or target bytes, @@ -679,6 +720,13 @@ instruction restoration differences; instruction `sections` and `changedPrompts` are empty because install never resolves new content. 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` +beside its `heading`. The export report lists `scopes`, the user scope first, +each with `scope`, absolute `root`, `status` (`locked`, `missingLock`, +`pendingRecovery` or `unavailable` with a `message`), `targets` (each with its +lock key `target`, sorted `agents`, optional `import` for a Claude forwarding +file, and the `sections` it receives), `unplaced` sections and `prompts`. + Watch `sources` entries (and the single diff `source` object) include `alias`, normalized `source`, `seen`, `current`, optional Git `commitCount`, and `changes`. Each baseline is either `{ "revision": "" }` or diff --git a/Documentation/Reference/Schemas/install.schema.json b/Documentation/Reference/Schemas/install.schema.json index f0c61ed..a5c5775 100644 --- a/Documentation/Reference/Schemas/install.schema.json +++ b/Documentation/Reference/Schemas/install.schema.json @@ -1,10 +1,10 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Skill and instruction restoration, version 1", + "title": "Skill and instruction restoration, version 2", "type": "object", "properties": { "schemaVersion": { - "const": 1 + "const": 2 }, "scope": { "enum": [ diff --git a/Documentation/Reference/Schemas/instructions-export.schema.json b/Documentation/Reference/Schemas/instructions-export.schema.json new file mode 100644 index 0000000..b213994 --- /dev/null +++ b/Documentation/Reference/Schemas/instructions-export.schema.json @@ -0,0 +1,108 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "Instruction export, version 1", + "type": "object", + "properties": { + "schemaVersion": { + "const": 1 + }, + "scopes": { + "type": "array", + "items": { + "type": "object", + "properties": { + "scope": { + "enum": [ + "project", + "user" + ] + }, + "root": { + "type": "string" + }, + "status": { + "enum": [ + "locked", + "missingLock", + "pendingRecovery", + "unavailable" + ] + }, + "message": { + "type": "string" + }, + "targets": { + "type": "array", + "items": { + "type": "object", + "properties": { + "target": { + "type": "string" + }, + "agents": { + "type": "array", + "items": { + "type": "string" + } + }, + "import": { + "type": "string" + }, + "sections": { + "type": "array", + "items": { + "$ref": "instructions.schema.json#/$defs/section" + } + } + }, + "required": [ + "target", + "agents", + "sections" + ] + } + }, + "unplaced": { + "type": "array", + "items": { + "$ref": "instructions.schema.json#/$defs/section" + } + }, + "prompts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string" + }, + "sections": { + "type": "array", + "items": { + "$ref": "instructions.schema.json#/$defs/section" + } + } + }, + "required": [ + "name", + "sections" + ] + } + } + }, + "required": [ + "scope", + "root", + "status", + "targets", + "unplaced", + "prompts" + ] + } + } + }, + "required": [ + "schemaVersion", + "scopes" + ] +} diff --git a/Documentation/Reference/Schemas/instructions-installed-list.schema.json b/Documentation/Reference/Schemas/instructions-installed-list.schema.json index 611ad95..b8c60d7 100644 --- a/Documentation/Reference/Schemas/instructions-installed-list.schema.json +++ b/Documentation/Reference/Schemas/instructions-installed-list.schema.json @@ -35,12 +35,6 @@ "type": "string" } }, - "headingOffset": { - "enum": [ - 0, - 1 - ] - }, "import": { "type": "string" }, diff --git a/Documentation/Reference/Schemas/instructions-source-list.schema.json b/Documentation/Reference/Schemas/instructions-source-list.schema.json index faf26c1..a907391 100644 --- a/Documentation/Reference/Schemas/instructions-source-list.schema.json +++ b/Documentation/Reference/Schemas/instructions-source-list.schema.json @@ -26,6 +26,20 @@ "heading": { "type": "string" }, + "level": { + "type": "integer", + "minimum": 1, + "maximum": 6 + }, + "description": { + "type": "string" + }, + "paths": { + "type": "array", + "items": { + "type": "string" + } + }, "section": { "$ref": "instructions.schema.json#/$defs/section" } diff --git a/Documentation/Reference/Schemas/instructions-update.schema.json b/Documentation/Reference/Schemas/instructions-update.schema.json index 10843cc..78d299e 100644 --- a/Documentation/Reference/Schemas/instructions-update.schema.json +++ b/Documentation/Reference/Schemas/instructions-update.schema.json @@ -1,10 +1,10 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Instruction update preview, version 1", + "title": "Instruction update preview, version 2", "type": "object", "properties": { "schemaVersion": { - "const": 1 + "const": 2 }, "scope": { "enum": [ diff --git a/Documentation/Reference/Schemas/instructions.schema.json b/Documentation/Reference/Schemas/instructions.schema.json index 9cd45eb..c629845 100644 --- a/Documentation/Reference/Schemas/instructions.schema.json +++ b/Documentation/Reference/Schemas/instructions.schema.json @@ -1,6 +1,6 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Instruction report definitions, version 1", + "title": "Instruction report definitions, version 2", "$defs": { "section": { "type": "object", @@ -123,40 +123,11 @@ "enum": [ "clean", "drifted", - "missingBlock" + "missing" ] }, - "adoptedSections": { - "type": "array", - "items": { - "type": "string" - } - }, - "conflicts": { - "type": "array", - "items": { - "type": "object", - "properties": { - "section": { - "type": "string" - }, - "existing": { - "type": "string" - }, - "proposed": { - "type": "string" - }, - "difference": { - "type": "string" - } - }, - "required": [ - "section", - "existing", - "proposed", - "difference" - ] - } + "foreign": { + "type": "boolean" } }, "required": [ @@ -166,8 +137,7 @@ "agentsChanged", "beforeAgents", "afterAgents", - "adoptedSections", - "conflicts" + "foreign" ] } }, diff --git a/Documentation/Reference/Schemas/update.schema.json b/Documentation/Reference/Schemas/update.schema.json index f7e07e8..c8165db 100644 --- a/Documentation/Reference/Schemas/update.schema.json +++ b/Documentation/Reference/Schemas/update.schema.json @@ -1,10 +1,10 @@ { "$schema": "https://json-schema.org/draft/2020-12/schema", - "title": "Skill and instruction update preview, version 1", + "title": "Skill and instruction update preview, version 2", "type": "object", "properties": { "schemaVersion": { - "const": 1 + "const": 2 }, "scope": { "enum": [ diff --git a/Package.resolved b/Package.resolved index c637a77..3ed545f 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "eef585af6215c4295fb0b1ff40e749b5f7836707d2f1ff9f8b77a5d6a39a4822", + "originHash" : "586b1f666f366ef83112773c577dff68045cc8c33f80d0d3326da317163ec154", "pins" : [ { "identity" : "core", "kind" : "remoteSourceControl", "location" : "https://github.com/agents-tools/core.git", "state" : { - "revision" : "b4c17da9d1bb908de1c15de61422ec2e1ad80e0d", - "version" : "0.1.2" + "revision" : "65df60ef97ff6d347b6944372a1b75de919313fe", + "version" : "0.2.0" } }, { diff --git a/Package.swift b/Package.swift index 3700ce7..4a9a622 100644 --- a/Package.swift +++ b/Package.swift @@ -8,9 +8,7 @@ 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.1.2"..<"0.2.0"), + .package(url: "https://github.com/agents-tools/core.git", "0.2.0"..<"0.3.0"), ], targets: [ .executableTarget( diff --git a/README.md b/README.md index 3b95591..7bf097e 100644 --- a/README.md +++ b/README.md @@ -54,8 +54,8 @@ an upstream change: ## Install -Version 0.1.2 and development builds require macOS 15 or later. Earlier -releases retain their original requirements. +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: @@ -92,8 +92,11 @@ agents skills add https://github.com/anthropics/skills.git --all --agent codex agents skills list agents skills list --scope user --json agents instructions add /path/to/rules canonical-artifacts +agents instructions init review +agents instructions add . review agents instructions list agents instructions update --apply +agents instructions export --json agents instructions render chatgpt weekly | pbcopy agents watch add https://github.com/anthropics/skills.git agents watch @@ -114,11 +117,15 @@ selected with `--scope user`. Commands never prompt for confirmation. changes since the last `watch seen`, and previews file differences. Removing a subscription with `watch remove` keeps installed skills and instructions. -Instructions are Markdown sections discovered in a source's `instructions/` or -`.agents/instructions/` directory. Managed blocks preserve surrounding custom -content in agent files, with Claude forwarding where needed. `--agent` on -instructions add, remove, or update sets the recipients of the scope's entire -section list. `agents instructions init ` creates `.md`. +Instructions are Markdown files with front matter, discovered in a source's +`instructions/` or `.agents/instructions/` directory, or in the project's own +`.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. +`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 `agents instructions update --apply`; render emits only their locked sections @@ -161,7 +168,7 @@ 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.1.2"..<"0.2.0"`. To use a local core +Core uses the published version range `"0.2.0"..<"0.3.0"`. To use a local core worktree without changing the package manifest: ```sh diff --git a/Sources/CLI/EntryPoint.swift b/Sources/CLI/EntryPoint.swift index db052e7..aac60de 100644 --- a/Sources/CLI/EntryPoint.swift +++ b/Sources/CLI/EntryPoint.swift @@ -3,7 +3,7 @@ import Darwin import Foundation enum BuildInfo { - static let version = "0.1.2" + static let version = "0.2.0" } struct Agents: ParsableCommand { diff --git a/Sources/CLI/InstructionCommands.swift b/Sources/CLI/InstructionCommands.swift index 553f100..0fd8beb 100644 --- a/Sources/CLI/InstructionCommands.swift +++ b/Sources/CLI/InstructionCommands.swift @@ -9,7 +9,8 @@ struct InstructionsCommand: ParsableCommand { abstract: "Add, inspect, render, and maintain instructions.", subcommands: [ AddInstructions.self, ListInstructions.self, RemoveInstructions.self, - UpdateInstructions.self, RenderInstructions.self, InitializeInstructions.self, + UpdateInstructions.self, RenderInstructions.self, ExportInstructions.self, + InitializeInstructions.self, ]) } @@ -32,19 +33,20 @@ struct AddInstructions: ParsableCommand { @Argument( help: - "Git URL, local Git directory, or declared source alias, optionally followed by selectors such as @branch:main." + "Git URL, local Git directory or declared source alias, optionally followed by selectors such as @branch:main; '.' selects the project's own instructions in .agent/instructions." ) var source: String @Argument( help: - "Sections to add in order. Omit to add the source's only section, or to list the choices when it has several." + "Instructions files to add in order, by name. Omit to add the source's only file, or to list the choices when it has several." ) var names: [String] = [] @OptionGroup var location: ScopeOptions @OptionGroup var agents: InstructionAgentOptions @OptionGroup var discovery: SourcePathOptions @OptionGroup var requirements: RequirementOptions - @Flag(help: "Show differences, then replace conflicting custom sections.") var replace = false + @Flag(help: "Show differences, then take over target files that agents did not generate.") + var replace = false func run() throws { let outcome = try withRecovery { @@ -54,19 +56,28 @@ struct AddInstructions: ParsableCommand { scope: location.scope, path: discovery.path, sourceRequirement: requirements.requirement), beforeApply: { Terminal.instructionTargets( - $0.targets.filter { !$0.assembly.conflicts.isEmpty }, paths: location.paths) + $0.targets.filter(\.foreign), paths: location.paths) }) } if outcome.result == nil { 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.map { $0.record.name } : names + 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 } Terminal.write( - "Added \(selected.map(Terminal.line).joined(separator: ", ")) to \(location.paths.path(target.url.path)) (\(Terminal.recipients(target.afterAgents))).\n" + "Added \(added.joined(separator: ", ")) to \(location.paths.path(target.url.path)) (\(Terminal.recipients(target.afterAgents))).\n" ) } } @@ -76,9 +87,13 @@ struct AddInstructions: ParsableCommand { struct ListInstructions: ParsableCommand { static let configuration = CommandConfiguration( commandName: "list", - abstract: "List managed sections and targets, or discover sections in a source.") + abstract: "List managed sections and targets, or the instructions files a source provides.") - @Argument(help: "Inspect this source instead of managed instructions.") var source: String? + @Argument( + help: + "Inspect this source instead of managed instructions; '.' lists the project's own instructions." + ) + var source: String? @OptionGroup var location: ScopeOptions @OptionGroup var discovery: SourcePathOptions @Flag(help: "Print the versioned JSON report.") var json = false @@ -149,9 +164,15 @@ struct UpdateInstructions: ParsableCommand { @OptionGroup var options: UpdateOptions @OptionGroup var agents: InstructionAgentOptions + @Flag(help: "With --apply, take over target files that agents did not generate.") + var replace = false + + func validate() throws { + if replace && !options.apply { throw ValidationError("--replace requires --apply") } + } func run() throws { - let result = try options.updateInstructions(agents: agents.recipients) + let result = try options.updateInstructions(agents: agents.recipients, replace: replace) if options.json { try Terminal.json( InstructionPreviewReport( @@ -197,17 +218,52 @@ struct RenderChatGPT: ParsableCommand { } } +struct ExportInstructions: ParsableCommand { + static let configuration = CommandConfiguration( + commandName: "export", + abstract: "Print the locked mapping of instruction targets to sections.", + discussion: + "Reads the user scope and each project root's lock without writing. Without --root, the current directory is the project root." + ) + + @Option( + name: .long, parsing: .upToNextOption, + help: "Include these project directories. Repeat for several.") + var root: [String] = [] + @Flag(help: "Print the versioned JSON report.") var json = false + + func run() throws { + let environment = RuntimeEnvironment() + let roots = (root.isEmpty ? [environment.projectDirectory.path] : root).map { + URL(fileURLWithPath: $0, relativeTo: environment.projectDirectory).standardizedFileURL + } + for project in roots { + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: project.path, isDirectory: &isDirectory), + isDirectory.boolValue + else { + throw CoreError.notFound("project directory \(project.path); provide an existing --root") + } + } + let mappings = InstructionOperations.export(projectRoots: roots, environment: environment) + if json { + try Terminal.json(InstructionExportReport(mappings)) + } else { + Terminal.instructionMappings(mappings, paths: HumanPaths()) + } + } +} + struct InitializeInstructions: ParsableCommand { static let configuration = CommandConfiguration( commandName: "init", - abstract: "Create a named instructions Markdown file in the current directory.") + abstract: "Create an instructions file with front matter in the project's .agent/instructions.") - @Argument(help: "New instruction file name, without the .md extension.") var name: String + @Argument(help: "New instructions file name, without the .md extension.") var name: String func run() throws { let file = try withRecovery { - try InstructionOperations.initializeInstructions( - named: name, directory: URL(fileURLWithPath: FileManager.default.currentDirectoryPath)) + try InstructionOperations.initializeInstructions(named: name) } Terminal.write("Created \(HumanPaths().path(file.path)).\n") } diff --git a/Sources/CLI/InstructionReports.swift b/Sources/CLI/InstructionReports.swift index 2e7bab7..fd03067 100644 --- a/Sources/CLI/InstructionReports.swift +++ b/Sources/CLI/InstructionReports.swift @@ -36,10 +36,16 @@ struct InstructionSourceReport: Encodable { struct AvailableSection: Encodable { let heading: String + let level: Int + let description: String + let paths: [String] let section: SectionItem init(_ unit: InstructionUnit) { heading = unit.section.heading + level = unit.section.level + description = unit.section.description + paths = unit.section.paths section = SectionItem(unit.record) } } @@ -67,7 +73,6 @@ struct InstructionListReport: Encodable { struct InstructionTargetItem: Encodable { let target: String let agents: [String] - let headingOffset: Int? let `import`: String? let blockHash: String let created: Bool @@ -75,7 +80,6 @@ struct InstructionTargetItem: Encodable { init(target: String, record: LockedTarget) { self.target = target agents = record.agents.map(\.rawValue).sorted() - headingOffset = record.headingOffset `import` = record.import blockHash = record.blockHash created = record.created @@ -95,7 +99,7 @@ struct PromptItem: Encodable { } struct InstructionPreviewReport: Encodable { - let schemaVersion = 1 + let schemaVersion = 2 let scope: String let changed: Bool let instructions: InstructionChanges @@ -143,8 +147,7 @@ struct InstructionTargetChangeItem: Encodable { let before: FileEntry? let after: FileEntry? let drift: String? - let adoptedSections: [String] - let conflicts: [InstructionConflictItem] + let foreign: Bool init(_ change: InstructionTargetChange) { target = change.target @@ -158,16 +161,15 @@ struct InstructionTargetChangeItem: Encodable { switch change.drift { case .clean: drift = "clean" case .drifted: drift = "drifted" - case .missingBlock: drift = "missingBlock" + case .missing: drift = "missing" case nil: drift = nil } - adoptedSections = change.assembly.adoptedSections - conflicts = change.assembly.conflicts.map(InstructionConflictItem.init) + foreign = change.foreign } private enum CodingKeys: String, CodingKey { case target, path, changed, agentsChanged, beforeAgents, afterAgents - case before, after, drift, adoptedSections, conflicts + case before, after, drift, foreign } func encode(to encoder: any Encoder) throws { @@ -181,27 +183,66 @@ struct InstructionTargetChangeItem: Encodable { try container.encodeIfPresent(before, forKey: .before) try container.encodeIfPresent(after, forKey: .after) try container.encodeIfPresent(drift, forKey: .drift) - try container.encode(adoptedSections, forKey: .adoptedSections) - try container.encode(conflicts, forKey: .conflicts) + try container.encode(foreign, forKey: .foreign) + } +} + +struct InstructionExportReport: Encodable { + let schemaVersion = 1 + let scopes: [ScopeMapping] + + init(_ mappings: [InstructionMapping]) { + scopes = mappings.map(ScopeMapping.init) + } +} + +struct ScopeMapping: Encodable { + let scope: String + let root: String + let status: String + let message: String? + let targets: [TargetMapping] + let unplaced: [SectionItem] + let prompts: [PromptMapping] + + init(_ mapping: InstructionMapping) { + scope = mapping.scope.rawValue + root = mapping.root.path + switch mapping.status { + case .locked: (status, message) = ("locked", nil) + case .missingLock: (status, message) = ("missingLock", nil) + case .pendingRecovery: (status, message) = ("pendingRecovery", nil) + case .unavailable(let reason): (status, message) = ("unavailable", reason) + } + targets = mapping.targets.map(TargetMapping.init) + unplaced = mapping.unplaced.map(SectionItem.init) + prompts = mapping.prompts.sorted { $0.key < $1.key }.map { + PromptMapping(name: $0.key, sections: $0.value.map(SectionItem.init)) + } } } -struct InstructionConflictItem: Encodable { - let section: String - let existing: String - let proposed: String - let difference: String +struct TargetMapping: Encodable { + let target: String + let agents: [String] + let `import`: String? + let sections: [SectionItem] - init(_ conflict: InstructionConflict) { - section = conflict.sectionID - existing = conflict.existing - proposed = conflict.proposed - difference = conflict.difference + init(_ target: InstructionMapping.Target) { + self.target = target.target + agents = target.agents.map(\.rawValue).sorted() + `import` = target.import + sections = target.sections.map(SectionItem.init) } } +struct PromptMapping: Encodable { + let name: String + let sections: [SectionItem] +} + struct InstallReport: Encodable { - let schemaVersion = 1 + let schemaVersion = 2 let scope: String let skills: [RestoredSkill] let instructions: InstructionChanges diff --git a/Sources/CLI/JSONReports.swift b/Sources/CLI/JSONReports.swift index e401f24..7a63162 100644 --- a/Sources/CLI/JSONReports.swift +++ b/Sources/CLI/JSONReports.swift @@ -68,7 +68,7 @@ struct AvailableItem: Encodable { } struct UpdateReport: Encodable { - let schemaVersion = 1 + let schemaVersion = 2 let scope: String let changed: Bool let skills: [UpdateItem] @@ -262,7 +262,8 @@ struct CheckItem: Encodable { kind = "instructions" id = diagnostic.kind.rawValue switch diagnostic.kind { - case .invalidTarget, .conflict, .invalidConfiguration, .stateUnavailable, .pendingRecovery: + case .invalidTarget, .foreignTarget, .invalidLink, .invalidConfiguration, .stateUnavailable, + .pendingRecovery: status = "error" default: status = "warning" diff --git a/Sources/CLI/LifecycleCommands.swift b/Sources/CLI/LifecycleCommands.swift index ad91a7e..7c9a90c 100644 --- a/Sources/CLI/LifecycleCommands.swift +++ b/Sources/CLI/LifecycleCommands.swift @@ -71,12 +71,12 @@ struct UpdateOptions: ParsableArguments { } } - func updateInstructions(agents: [AgentID]? = nil) throws + func updateInstructions(agents: [AgentID]? = nil, replace: Bool = false) throws -> InstructionUpdateReport { try withRecovery { try InstructionOperations.updateInstalled( - scope: location.scope, agents: agents, apply: apply, + scope: location.scope, agents: agents, apply: apply, replace: replace, beforeApply: { result in Terminal.instructionDifferences(result, paths: location.paths) }) diff --git a/Sources/CLI/Terminal.swift b/Sources/CLI/Terminal.swift index 8997aaa..e022d86 100644 --- a/Sources/CLI/Terminal.swift +++ b/Sources/CLI/Terminal.swift @@ -107,14 +107,25 @@ enum Terminal { action = "check the scope's agents.json, agents.resolved, and recovery journal" case CoreError.commandFailed: action = "check the command arguments and filesystem permissions" - case InstructionError.conflictingSections: - if command is AddInstructions { + case InstructionError.unownedTargets: + if command is AddInstructions || command is UpdateInstructions { action = - "inspect the differences and rerun with --replace to replace the conflicting custom sections" + "move what those files need into instructions files, then rerun with --replace to take them over" + } else if command is Install || command is RemoveInstructions { + action = + "move those files aside and retry, then put what they need into instructions files" } else { action = - "edit or remove the conflicting custom sections in the target file, or rerun 'agents instructions add' with --replace, then retry" + "move what those files need into instructions files, then run 'agents instructions update --apply --replace'" } + case InstructionError.invalidLockedBlock: + action = + "run 'agents instructions update --apply' to regenerate the targets, adding --replace to take over files that agents did not generate" + case InstructionError.ownChanged: + action = "run 'agents instructions update --apply' to regenerate targets from the edited file" + case InstructionError.invalidLinks: + action = + "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'" @@ -221,10 +232,46 @@ enum Terminal { static func availableInstructions(_ sections: [InstructionUnit]) { if sections.isEmpty { write("No instruction sections found in source.\n") } for unit in sections { - write("\(line(unit.record.name)) \(line(unit.section.heading))\n") + write( + "\(line(unit.record.name)) \(line(unit.section.heading)) \(line(unit.section.description))\n" + ) } } + static func instructionMappings(_ mappings: [InstructionMapping], paths: HumanPaths) { + for mapping in mappings { + let status: String + switch mapping.status { + case .locked: status = "" + case .missingLock: status = " no lock" + case .pendingRecovery: status = " recovery pending" + case .unavailable(let reason): status = " unavailable: " + line(reason) + } + let root = HumanPaths(scope: mapping.scope, environment: paths.environment) + .path(mapping.root.path) + write("\(root) (\(mapping.scope.rawValue))\(status)\n") + for target in mapping.targets { + let imported = target.import.map { " imports " + line($0) } ?? "" + write( + " \(paths.path(target.target)) \(recipients(target.agents))\(imported)\n") + for section in target.sections { write(mappedSection(section, paths: paths)) } + } + if !mapping.unplaced.isEmpty { write(" Unplaced\n") } + for section in mapping.unplaced { write(mappedSection(section, paths: paths)) } + for (name, sections) in mapping.prompts.sorted(by: { $0.key < $1.key }) { + write(" ChatGPT \(line(name))\n") + for section in sections { write(mappedSection(section, paths: paths)) } + } + } + } + + private static func mappedSection(_ section: LockedSection, paths: HumanPaths) -> String { + let pinned = section.revision != nil || section.version != nil + let pin = + pinned ? " " + line(HumanItem.pin(revision: section.revision, version: section.version)) : "" + return " \(line(section.name)) \(paths.source(section.source))\(pin)\n" + } + static func managedInstructions(_ report: InstructionListReport, paths: HumanPaths) { if report.sections.isEmpty && report.targets.isEmpty && report.prompts.isEmpty { write("No managed \(report.scope) instructions.\n") @@ -298,17 +345,15 @@ enum Terminal { static func instructionTargets(_ targets: [InstructionTargetChange], paths: HumanPaths) { for target in targets { let path = paths.path(target.url.path) - for section in target.assembly.adoptedSections { - write("Adopt \(line(section)) in \(path)\n") - } - for conflict in target.assembly.conflicts { - write("Conflict \(line(conflict.sectionID)) in \(path)\n") - } + if target.foreign { write("Take over \(path), which agents did not generate\n") } if target.agentsChanged { write( "Recipients of \(path): \(recipients(target.beforeAgents ?? [])) -> \(recipients(target.afterAgents))\n" ) } + if !target.changed, target.after != nil, target.afterAgents.isEmpty { + write("Left \(path) in place because it differs from its generated version\n") + } if target.changed { write( "\(path) (\(recipients(target.afterAgents.isEmpty ? target.beforeAgents ?? [] : target.afterAgents)))\n" diff --git a/Tests/CLITests/ExecutableTests.swift b/Tests/CLITests/ExecutableTests.swift index 257a48d..469cd20 100644 --- a/Tests/CLITests/ExecutableTests.swift +++ b/Tests/CLITests/ExecutableTests.swift @@ -52,7 +52,7 @@ struct ExecutableTests { Set(preview.keys) == [ "schemaVersion", "scope", "changed", "skills", "instructions", "lockMissing", ]) - #expect(preview["schemaVersion"] as? Int == 1 && preview["changed"] as? Bool == true) + #expect(preview["schemaVersion"] as? Int == 2 && preview["changed"] as? Bool == true) let updates = try #require(preview["skills"] as? [[String: Any]]) let update = try #require(updates.first) #expect( diff --git a/Tests/CLITests/InstructionExecutableTests.swift b/Tests/CLITests/InstructionExecutableTests.swift index 2f188fd..c3c5be1 100644 --- a/Tests/CLITests/InstructionExecutableTests.swift +++ b/Tests/CLITests/InstructionExecutableTests.swift @@ -1,3 +1,4 @@ +import AgentsInstructions import Foundation import Testing @@ -14,20 +15,13 @@ struct InstructionExecutableTests { scope == "project" ? fixture.project.appendingPathComponent("AGENTS.md") : fixture.home.appendingPathComponent(".codex/AGENTS.md") - try FileManager.default.createDirectory( - at: target.deletingLastPathComponent(), withIntermediateDirectories: true) - let custom = - "# Project Guide\n\nLocal introduction.\n\n## Local Rules\n\nKeep custom content.\n" - try Data(custom.utf8).write(to: target) try fixture.success( [ "instructions", "add", fixture.source.path, "canonical-artifacts", "--agent", "codex", "--branch", "main", ] + arguments) let original = try String(contentsOf: target, encoding: .utf8) - #expect(original.contains("## Canonical Artifacts\n\nOriginal instructions")) - #expect(original.hasPrefix("# Project Guide\n\nLocal introduction.\n")) - #expect(original.hasSuffix("## Local Rules\n\nKeep custom content.\n")) + #expect(original == generated(["# Canonical Artifacts\n\nOriginal instructions"])) let list = try fixture.success(["instructions", "list", "--json"] + arguments).json() #expect(Set(list.keys) == ["schemaVersion", "kind", "scope", "sections", "targets", "prompts"]) #expect(list["schemaVersion"] as? Int == 1 && list["kind"] as? String == "installed") @@ -35,7 +29,6 @@ struct InstructionExecutableTests { #expect(sections.count == 1 && sections.first?["name"] as? String == "canonical-artifacts") let targets = try #require(list["targets"] as? [[String: Any]]) #expect(targets.first?["agents"] as? [String] == ["codex"]) - #expect(targets.first?["created"] as? Bool == false) let humanList = try fixture.success(["instructions", "list"] + arguments) #expect(humanList.stdout.contains("canonical-artifacts") && humanList.stdout.contains("Target")) let drift = original.replacingOccurrences(of: "Original instructions", with: "Manual drift") @@ -56,12 +49,14 @@ struct InstructionExecutableTests { #expect(preview.stdout.contains("Changed ChatGPT prompt weekly.")) let json = try fixture.success(["instructions", "update", "--json"] + arguments).json() #expect(Set(json.keys) == ["schemaVersion", "scope", "changed", "instructions"]) + #expect(json["schemaVersion"] as? Int == 2) let changes = try #require(json["instructions"] as? [String: Any]) #expect(changes["changedPrompts"] as? [String] == ["weekly"]) let files = try #require(changes["targets"] as? [[String: Any]]) let before = try #require(files.first?["before"] as? [String: String]) #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.resolved", scope: scope)) == lock) #expect(try Data(contentsOf: target) == Data(drift.utf8)) @@ -72,6 +67,7 @@ struct InstructionExecutableTests { #expect(diffIndex < appliedIndex) #expect(applied.stdout.contains("Changed ChatGPT prompt weekly.")) let expected = try Data(contentsOf: target) + #expect(expected == Data(generated(["# Canonical Artifacts\n\nUpdated instructions"]).utf8)) let updatedLock = try Data(contentsOf: fixture.state("agents.resolved", scope: scope)) try Data(drift.utf8).write(to: target) try fixture.success(["install"] + arguments) @@ -86,11 +82,7 @@ struct InstructionExecutableTests { let pinned = try fixture.success(["instructions", "render", "chatgpt", "weekly"] + arguments) #expect(pinned.stdout == rendered.stdout) try fixture.success(["instructions", "remove", "canonical-artifacts"] + arguments) - let remainingCustom = try String(contentsOf: target, encoding: .utf8) - // Core owns the blank lines adjacent to the managed block. - #expect( - remainingCustom - == "# Project Guide\n\nLocal introduction.\n## Local Rules\n\nKeep custom content.\n") + #expect(!FileManager.default.fileExists(atPath: target.path)) let empty = try fixture.success(["instructions", "list", "--json"] + arguments).json() #expect((empty["sections"] as? [Any])?.isEmpty == true) #expect((empty["targets"] as? [Any])?.isEmpty == true) @@ -100,7 +92,7 @@ struct InstructionExecutableTests { #expect(missingPrompt.status == 1 && missingPrompt.stdout.isEmpty) } - @Test func sourceSelectionAndReplacement() throws { + @Test func sourceSelectionAndTakeover() throws { let fixture = try CLIFixture() try fixture.instruction(container: "collection/instructions") try fixture.instruction("other", heading: "Other Rules", container: "collection/instructions") @@ -108,29 +100,34 @@ struct InstructionExecutableTests { let sourceArguments = [fixture.source.path, "--path", "collection"] 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)) let discovered = try fixture.success(["instructions", "list"] + sourceArguments + ["--json"]) .json() #expect(discovered["kind"] as? String == "source") let sections = try #require(discovered["sections"] as? [[String: Any]]) #expect(sections.count == 2 && sections.first?["heading"] as? String == "Canonical Artifacts") + #expect(sections.first?["level"] as? Int == 1) + #expect(sections.first?["description"] as? String == "Canonical Artifacts rules.") + #expect(sections.first?["paths"] as? [String] == []) let target = fixture.project.appendingPathComponent("AGENTS.md") - let custom = "# Guide\n\n## Canonical Artifacts\n\nConflicting custom content\n" + let custom = "# Guide\n\nHand-written content\n" try Data(custom.utf8).write(to: target) let add = [ "instructions", "add", fixture.source.path, "canonical-artifacts", "--path", "collection", ] - let conflict = try fixture.run(add) - #expect(conflict.status == 1 && conflict.stdout.isEmpty) + let refused = try fixture.run(add) + #expect(refused.status == 1 && refused.stdout.isEmpty) #expect( - conflict.stderr.contains("Conflicting custom content") - && conflict.stderr.hasSuffix( - "\n Inspect the differences and rerun with --replace to replace the conflicting custom sections.\n" + refused.stderr.contains("Files that agents did not generate are in the way: AGENTS.md.") + && refused.stderr.hasSuffix( + "\n Move what those files need into instructions files, then rerun with --replace to take them over.\n" )) #expect(try String(contentsOf: target, encoding: .utf8) == custom) #expect(!FileManager.default.fileExists(atPath: fixture.state("agents.resolved").path)) let replaced = try fixture.success(add + ["--replace"]) - #expect(replaced.stdout.contains("-Conflicting custom content")) + #expect(replaced.stdout.contains("Take over AGENTS.md, which agents did not generate\n")) + #expect(replaced.stdout.contains("-Hand-written content")) #expect(replaced.stdout.contains("+Original instructions")) try fixture.success(["instructions", "add", "source", "other"]) let declaration = try fixture.declaration() @@ -139,10 +136,7 @@ struct InstructionExecutableTests { instructions["sections"] as? [String] == ["source:canonical-artifacts", "source:other"]) } - @Test(arguments: [ - ["install"], ["instructions", "remove", "other"], - ]) - func conflictRemedy(_ arguments: [String]) throws { + @Test func editedTargetsFollowTheLockAndHandWrittenOnesNeedReplace() throws { let fixture = try CLIFixture() try fixture.instruction() try fixture.instruction("other", heading: "Other Rules") @@ -152,17 +146,166 @@ struct InstructionExecutableTests { "codex", ]) let target = fixture.project.appendingPathComponent("AGENTS.md") - try Data("# Canonical Artifacts\n\nConflicting custom content\n".utf8).write( - to: target) - let conflict = try fixture.run(arguments) - #expect(conflict.status == 1) + let original = try Data(contentsOf: target) + let edited = Data( + String(decoding: original, as: UTF8.self) + .replacingOccurrences(of: "Original instructions", with: "Hand edit.").utf8) + try edited.write(to: target) + try fixture.success(["install"]) + #expect(try Data(contentsOf: target) == original) + let handWritten = Data("Hand-written.\n".utf8) + try handWritten.write(to: target) + for arguments in [["install"], ["instructions", "remove", "other"]] { + let refused = try fixture.run(arguments) + #expect( + refused.status == 1 + && refused.stderr.hasSuffix( + "\n Move those files aside and retry, then put what they need into instructions files.\n" + )) + #expect(try Data(contentsOf: target) == handWritten) + } + try fixture.success(["instructions", "update", "--apply", "--replace"]) + try edited.write(to: target) + let removed = try fixture.success(["instructions", "remove", "other"]) + #expect(removed.stdout.contains("-Hand edit.")) + #expect( + try String(contentsOf: target, encoding: .utf8) + == generated(["# Canonical Artifacts\n\nOriginal instructions"])) + let kept = Data( + try String(contentsOf: target, encoding: .utf8) + .replacingOccurrences(of: "Original instructions", with: "Hand edit.").utf8) + try kept.write(to: target) + let left = try fixture.success(["instructions", "remove", "canonical-artifacts"]) + #expect( + left.stdout.contains( + "Left AGENTS.md in place because it differs from its generated version\n")) + #expect(try Data(contentsOf: target) == kept) + for arguments in [["install"], ["instructions", "remove", "other"]] { + let invalid = try fixture.run(arguments + ["--replace"]) + #expect(invalid.status == 64 && invalid.stderr.contains("Unknown option '--replace'")) + } + } + + @Test func updateApplyRewritesStateFromTheEarlierLayout() 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 standard = try files.map { try Data(contentsOf: $0) } + #expect(standard.allSatisfy { !String(decoding: $0, as: UTF8.self).contains("\" : ") }) + for file in files { + let object = try JSONSerialization.jsonObject(with: Data(contentsOf: file)) + let earlier = try JSONSerialization.data( + withJSONObject: object, options: [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]) + #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) + } + + @Test func addNamesTheSectionsEachTargetReceives() throws { + let fixture = try CLIFixture() + let render = fixture.project.appendingPathComponent("Sources/Render") + try FileManager.default.createDirectory(at: render, withIntermediateDirectories: true) + let own = fixture.project.appendingPathComponent(".agent/instructions") + try FileManager.default.createDirectory(at: own, withIntermediateDirectories: true) + try Data("---\ndescription: Guide.\n---\n# Guide\n\nRead the README.\n".utf8).write( + to: own.appendingPathComponent("guide.md")) + try Data( + "---\ndescription: Rendering.\npaths: [\"Sources/Render/**\"]\n---\n# Rendering\n\nKeep frames stable.\n" + .utf8 + ).write(to: own.appendingPathComponent("render.md")) + let added = try fixture.success([ + "instructions", "add", ".", "render", "guide", "--agent", "codex", + ]) + #expect( + added.stdout + == "Added guide to AGENTS.md (codex).\nAdded render to Sources/Render/AGENTS.md (codex).\n") #expect( - conflict.stderr.contains("Conflicting custom content") - && conflict.stderr.hasSuffix( - "\n Edit or remove the conflicting custom sections in the target file, or rerun 'agents instructions add' with --replace, then retry.\n" + try String(contentsOf: render.appendingPathComponent("AGENTS.md"), encoding: .utf8) + == generated([ + "# Rendering\n\nApplies when working on files matching `Sources/Render/**`.\n\nKeep frames stable." + ])) + } + + @Test func updateTakesOverHandWrittenTargetsOnlyWithReplace() throws { + let fixture = try CLIFixture() + try fixture.instruction() + try fixture.commit() + try fixture.success(["instructions", "add", fixture.source.path, "--agent", "codex"]) + let gemini = fixture.project.appendingPathComponent("GEMINI.md") + let custom = Data("# Gemini\n\nHand-written.\n".utf8) + try custom.write(to: gemini) + let arguments = ["instructions", "update", "--agent", "codex", "--agent", "gemini-cli"] + let preview = try fixture.success(arguments + ["--json"]).json() + let changes = try #require(preview["instructions"] as? [String: Any]) + let targets = try #require(changes["targets"] as? [[String: Any]]) + #expect(targets.first { $0["target"] as? String == "GEMINI.md" }?["foreign"] as? Bool == true) + let refused = try fixture.run(arguments + ["--apply"]) + #expect( + refused.status == 1 + && refused.stderr.hasSuffix( + "\n Move what those files need into instructions files, then rerun with --replace to take them over.\n" )) - let invalid = try fixture.run(arguments + ["--replace"]) - #expect(invalid.status == 64 && invalid.stderr.contains("Unknown option '--replace'")) + #expect(try Data(contentsOf: gemini) == custom) + let usage = try fixture.run(arguments + ["--replace"]) + #expect(usage.status == 64 && usage.stdout.isEmpty) + let applied = try fixture.success(arguments + ["--apply", "--replace"]) + #expect(applied.stdout.contains("Take over GEMINI.md, which agents did not generate\n")) + #expect( + try String(contentsOf: gemini, encoding: .utf8) + == generated(["# Canonical Artifacts\n\nOriginal instructions"])) + } + + @Test func ownInstructionsAndExport() throws { + let fixture = try CLIFixture() + let created = try fixture.success(["instructions", "init", "guide"]) + #expect(created.stdout == "Created .agent/instructions/guide.md.\n") + let own = fixture.project.appendingPathComponent(".agent/instructions/guide.md") + let listed = try fixture.success(["instructions", "list", ".", "--json"]).json() + let available = try #require((listed["sections"] as? [[String: Any]])?.first) + #expect((available["section"] as? [String: Any])?["source"] as? String == ".") + try fixture.success(["instructions", "add", ".", "guide", "--agent", "codex"]) + let target = fixture.project.appendingPathComponent("AGENTS.md") + #expect( + try String(contentsOf: target, encoding: .utf8) + == generated(["# guide\n\nWrite the instructions here."])) + let declaration = try fixture.declaration() + #expect((declaration["instructions"] as? [String: Any])?["sections"] as? [String] == ["guide"]) + try Data( + "---\ndescription: Guide.\n---\n# guide\n\nEdited instructions.\n".utf8 + ).write(to: own) + let install = try fixture.run(["install"]) + #expect( + install.status == 1 + && install.stderr.hasSuffix( + "\n Run 'agents instructions update --apply' to regenerate targets from the edited file.\n" + )) + try fixture.success(["instructions", "update", "--apply"]) + #expect(try String(contentsOf: target, encoding: .utf8).contains("Edited instructions.")) + let other = fixture.root.appendingPathComponent("other") + try FileManager.default.createDirectory(at: other, withIntermediateDirectories: true) + let export = try fixture.success([ + "instructions", "export", "--root", fixture.project.path, "--root", other.path, "--json", + ]).json() + #expect(export["schemaVersion"] as? Int == 1) + let scopes = try #require(export["scopes"] as? [[String: Any]]) + #expect(scopes.map { $0["scope"] as? String } == ["user", "project", "project"]) + #expect(scopes.map { $0["status"] as? String } == ["missingLock", "locked", "missingLock"]) + let mapped = try #require((scopes[1]["targets"] as? [[String: Any]])?.first) + #expect( + mapped["target"] as? String == "AGENTS.md" && mapped["agents"] as? [String] == ["codex"]) + let section = try #require((mapped["sections"] as? [[String: Any]])?.first) + #expect(section["name"] as? String == "guide" && section["source"] as? String == ".") + #expect(section["path"] as? String == ".agent/instructions/guide.md") + let human = try fixture.success(["instructions", "export"]) + #expect(human.stdout.contains(" AGENTS.md codex\n guide .\n")) + let fromHome = try fixture.success(["instructions", "export"], directory: fixture.home) + #expect(fromHome.stdout == "~ (user) no lock\n. (project) no lock\n") } @Test func recipientOnlyUpdate() throws { @@ -191,7 +334,7 @@ struct InstructionExecutableTests { #expect( Set(change.keys) == [ "target", "path", "changed", "agentsChanged", "beforeAgents", "afterAgents", - "before", "after", "drift", "adoptedSections", "conflicts", + "before", "after", "drift", "foreign", ]) #expect(change["changed"] as? Bool == false && change["agentsChanged"] as? Bool == true) #expect(change["beforeAgents"] as? [String] == ["codex"]) @@ -298,7 +441,7 @@ struct InstructionExecutableTests { #expect(checks.first?["kind"] as? String == "skills") #expect( checks.contains { - $0["kind"] as? String == "instructions" && $0["id"] as? String == "missingBlock" + $0["kind"] as? String == "instructions" && $0["id"] as? String == "drift" }) let lock = try Data(contentsOf: fixture.state("agents.resolved")) let restored = try fixture.success(["install", "--json"]).json() @@ -311,7 +454,7 @@ struct InstructionExecutableTests { try fixture.instruction(body: "Updated section") try fixture.commit() let preview = try fixture.success(["update", "--json"]).json() - #expect(preview["schemaVersion"] as? Int == 1 && preview["changed"] as? Bool == true) + #expect(preview["schemaVersion"] as? Int == 2 && preview["changed"] as? Bool == true) #expect((preview["skills"] as? [[String: Any]])?.first?["changed"] as? Bool == true) #expect( (preview["instructions"] as? [String: Any])?["changedPrompts"] as? [String] == ["weekly"]) @@ -338,8 +481,9 @@ struct InstructionExecutableTests { try fixture.success(["skills", "add", fixture.source.path, "pdf"]) try fixture.success(["instructions", "add", fixture.source.path]) let target = fixture.project.appendingPathComponent("AGENTS.md") - let invalid = try Data(contentsOf: target) + Data("\n\n".utf8) - try invalid.write(to: target) + let generatedTarget = try Data(contentsOf: target) + try Data("# Canonical Artifacts\n\nNo front matter.\n".utf8).write( + to: fixture.source.appendingPathComponent("instructions/canonical-artifacts.md")) try fixture.skill("pdf", body: "Updated content") try fixture.commit() let lock = try Data(contentsOf: fixture.state("agents.resolved")) @@ -352,19 +496,19 @@ struct InstructionExecutableTests { try String(contentsOf: fixture.project.appendingPathComponent(path), encoding: .utf8) .contains("Original content")) } - #expect(try Data(contentsOf: target) == invalid) + #expect(try Data(contentsOf: target) == generatedTarget) #expect(try Data(contentsOf: fixture.state("agents.resolved")) == lock) } } @Test func instructionDoctorErrorsAndFailedJSON() throws { let fixture = try CLIFixture() - try fixture.instruction() + try fixture.instruction(body: "Run [the checks](CONTRIBUTING.md).") try fixture.commit() + let contributing = fixture.project.appendingPathComponent("CONTRIBUTING.md") + try Data("Checks.\n".utf8).write(to: contributing) try fixture.success(["instructions", "add", fixture.source.path, "--agent", "codex"]) - let target = fixture.project.appendingPathComponent("AGENTS.md") - let original = try String(contentsOf: target, encoding: .utf8) - try Data((original + "\n\n").utf8).write(to: target) + try FileManager.default.removeItem(at: contributing) let doctor = try fixture.run(["doctor", "--json"]) #expect(doctor.status == 1 && doctor.stderr.isEmpty) let report = try doctor.json() @@ -373,14 +517,15 @@ struct InstructionExecutableTests { let checks = try #require(roots.first?["checks"] as? [[String: Any]]) #expect( checks.contains { - $0["id"] as? String == "invalidTarget" && $0["status"] as? String == "error" + $0["id"] as? String == "invalidLink" && $0["status"] as? String == "error" }) let failed = try fixture.run(["install", "--json"]) #expect(failed.status == 1 && failed.stdout.isEmpty) #expect(failed.stderr.split(separator: "\n").dropFirst().allSatisfy { $0.hasPrefix(" ") }) #expect( failed.stderr.hasSuffix( - "\n Check the instruction source and target Markdown with 'agents doctor'.\n")) + "\n Link only to files in the checkout being written, or name the file in text without a link.\n" + )) } @Test func emptyScopeReports() throws { @@ -422,10 +567,11 @@ struct InstructionExecutableTests { @Test func initialization() throws { let fixture = try CLIFixture() try fixture.success(["instructions", "init", "new-rules"]) - let file = fixture.project.appendingPathComponent("new-rules.md") + let file = fixture.project.appendingPathComponent(".agent/instructions/new-rules.md") #expect( try String(contentsOf: file, encoding: .utf8) - == "# new-rules\n\nWrite the instructions here.\n") + == "---\ndescription: Describe what these instructions make the agent do.\n---\n# new-rules\n\nWrite the instructions here.\n" + ) let duplicate = try fixture.run(["instructions", "init", "new-rules"]) #expect(duplicate.status == 1 && duplicate.stderr.contains("already exists")) } @@ -435,7 +581,8 @@ struct InstructionExecutableTests { ["instructions", "list", "--help"], ["instructions", "remove", "--help"], ["instructions", "update", "--help"], ["instructions", "render"], ["instructions", "render", "--help"], ["instructions", "render", "chatgpt", "--help"], - ["instructions", "init", "--help"], ["help", "instructions", "render", "chatgpt"], + ["instructions", "init", "--help"], ["instructions", "export", "--help"], + ["help", "instructions", "render", "chatgpt"], ]) func help(_ arguments: [String]) throws { let fixture = try CLIFixture() @@ -462,6 +609,11 @@ struct InstructionExecutableTests { } } +/// A generated target holding these section bodies. +func generated(_ sections: [String]) -> String { + Instructions.notice + "\n\n" + sections.joined(separator: "\n\n") + "\n" +} + extension CLIFixture { func instruction( _ name: String = "canonical-artifacts", heading: String = "Canonical Artifacts", @@ -469,7 +621,7 @@ extension CLIFixture { ) throws { let directory = source.appendingPathComponent(container) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) - try Data("# \(heading)\n\n\(body)\n".utf8).write( + try Data("---\ndescription: \(heading) rules.\n---\n# \(heading)\n\n\(body)\n".utf8).write( to: directory.appendingPathComponent(name + ".md")) } diff --git a/Tests/CLITests/SourceSelectorTests.swift b/Tests/CLITests/SourceSelectorTests.swift index c83cd9a..4ee6ebd 100644 --- a/Tests/CLITests/SourceSelectorTests.swift +++ b/Tests/CLITests/SourceSelectorTests.swift @@ -27,7 +27,7 @@ struct SourceSelectorTests { let fixture = try CLIFixture() let instructions = fixture.source.appendingPathComponent("instructions") try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) - try Data("# Rules\n\nFollow them.\n".utf8).write( + try Data("---\ndescription: Rules.\n---\n# Rules\n\nFollow them.\n".utf8).write( to: instructions.appendingPathComponent("rules.md")) try fixture.commit() let rejected = try fixture.run([ diff --git a/Tests/CLITests/UpdateReportingTests.swift b/Tests/CLITests/UpdateReportingTests.swift index 25004ff..d2bb405 100644 --- a/Tests/CLITests/UpdateReportingTests.swift +++ b/Tests/CLITests/UpdateReportingTests.swift @@ -24,7 +24,7 @@ struct UpdateReportingTests { let newRevision = try fixture.git(["rev-parse", "HEAD"]).stdout.trimmingCharacters( in: .whitespacesAndNewlines) let report = try fixture.success(command + ["--json"]).json() - #expect(report["schemaVersion"] as? Int == 1) + #expect(report["schemaVersion"] as? Int == 2) let skill = try #require((report["skills"] as? [[String: Any]])?.first) #expect(skill["oldVersion"] as? String == "1.2.0") #expect(skill["newVersion"] as? String == "1.3.0")