From db6e1c77628d3ede0e12861dba7ace7b22c870ac Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:45:01 +0800 Subject: [PATCH 01/18] feat(instructions)!: generate targets from instruction files Instruction files carry front matter with a required description and optional paths, may sit in subdirectories, and are named by their container-relative path. A project's own files in .agent/instructions are read from the working tree and selected by bare name. Targets are generated in full from the selected sections: a notice line followed by the bodies as written. Sections with paths are scoped by a line after their first heading and, in project scope, written to the AGENTS.md of the directory their patterns share. Managed blocks, title detection, heading offsets and adoption are removed; writing over a file agents did not generate requires replace. Local links must resolve in the checkout being written. Doctor reports hand-written targets, changed own files and broken links, and its Codex size check now budgets only the project chain. Export maps locked targets to their sections. --- CHANGELOG.md | 42 ++ Documentation/Architecture/Instructions.md | 194 ++++++--- Documentation/Architecture/Package.md | 94 ++--- Documentation/Architecture/State.md | 8 +- Documentation/Architecture/Watch.md | 5 +- Documentation/Proposals/AgentInstructions.md | 318 ++++++++------ README.md | 61 +-- Sources/AgentsCore/Declaration.swift | 19 +- Sources/AgentsCore/InstructionLocations.swift | 18 +- Sources/AgentsCore/ResolvedState.swift | 19 +- Sources/AgentsCore/TransactionPaths.swift | 4 +- Sources/AgentsCore/WatchOperations.swift | 26 +- .../InstructionDoctor.swift | 178 +++++--- .../InstructionExport.swift | 98 +++++ .../InstructionFrontMatter.swift | 81 ++++ .../InstructionLifecycleModels.swift | 18 +- .../InstructionModels.swift | 101 ++--- .../InstructionOperations.swift | 126 +++--- .../InstructionSources.swift | 117 +++++- .../InstructionTargets.swift | 255 ++++++++---- .../InstructionUpdatePlan.swift | 8 +- Sources/AgentsInstructions/Instructions.swift | 392 +++++++++--------- .../AgentsInstructions/MarkdownDocument.swift | 48 --- .../InstructionTransactionTests.swift | 13 + Tests/AgentsCoreTests/StateModelTests.swift | 50 +++ .../WatchDurabilityTests.swift | 4 +- .../WatchMirrorConcurrencyTests.swift | 2 +- .../AssemblyTests.swift | 339 --------------- .../ClaudeForwardingTests.swift | 204 +++++++++ .../DoctorLifecycleTests.swift | 62 ++- .../GenerationTests.swift | 85 ++++ .../LifecycleFixture.swift | 44 +- .../LifecycleSafetyTests.swift | 24 +- .../LifecycleTests.swift | 101 +++-- .../ReferenceAndForwardingTests.swift | 151 ------- .../RenderingTests.swift | 184 -------- .../SemanticTextTests.swift | 192 --------- .../AgentsInstructionsTests/SourceTests.swift | 130 ------ .../StructureTests.swift | 231 ----------- .../TargetLifecycleTests.swift | 150 +++++++ .../UnitFormatTests.swift | 104 +++++ .../AutomaticSelectionTests.swift | 5 +- .../ReadOnlyInspectionTests.swift | 12 +- .../WatchSubscriptionTests.swift | 15 + .../CombinedUpdateTests.swift | 26 +- Tests/AgentsUpdatesTests/UpdateFixture.swift | 4 +- 46 files changed, 2218 insertions(+), 2144 deletions(-) create mode 100644 Sources/AgentsInstructions/InstructionExport.swift create mode 100644 Sources/AgentsInstructions/InstructionFrontMatter.swift delete mode 100644 Tests/AgentsInstructionsTests/AssemblyTests.swift create mode 100644 Tests/AgentsInstructionsTests/ClaudeForwardingTests.swift create mode 100644 Tests/AgentsInstructionsTests/GenerationTests.swift delete mode 100644 Tests/AgentsInstructionsTests/ReferenceAndForwardingTests.swift delete mode 100644 Tests/AgentsInstructionsTests/RenderingTests.swift delete mode 100644 Tests/AgentsInstructionsTests/SemanticTextTests.swift delete mode 100644 Tests/AgentsInstructionsTests/SourceTests.swift delete mode 100644 Tests/AgentsInstructionsTests/StructureTests.swift create mode 100644 Tests/AgentsInstructionsTests/TargetLifecycleTests.swift create mode 100644 Tests/AgentsInstructionsTests/UnitFormatTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index d152ebf..1a848df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,48 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +### Added + +- Instructions files may sit in subdirectories of `instructions/` and + `.agents/instructions/`; a file's name is its container-relative path, such + as `epd/review`. +- A project's own instructions in `.agent/instructions/` are selected by bare + name and read from the working tree. `InstructionAddOptions(source: ".")` + adds them; `listOwn(environment:)` lists them. +- Front matter `paths` scopes a section: its patterns are named after its first + heading, and in project scope the section is written to the `AGENTS.md` of + the directory the patterns share. +- `InstructionOperations.export(projectRoots:environment:)` maps the locked + targets of the user scope and given projects to their sections. +- Doctor reports hand-written files in target locations, own files changed + since the lock, and links in generated targets that no longer resolve. + +### Changed + +- **Breaking:** an instructions file needs front matter with a `description`, + and its body may start at any heading level. Add front matter to existing + files; headings are written as authored. +- **Breaking:** targets are generated in full: a notice line followed by the + sections. Custom content in targets, managed blocks, title detection, heading + offsets and adoption of matching custom sections are gone. Move hand-written + content into instructions files. Writing over a file that agents did not + generate needs `replace`; `InstructionError.unownedTargets` names it. +- **Breaking:** `InstructionTargetChange.assembly` is replaced by `foreign`, + and `InstructionDrift` is `clean`, `drifted` or `missing`. Diagnostic kinds + `missingBlock`, `adoption` and `conflict` become `missingTarget`, + `foreignTarget`, `ownChanged` and `invalidLink`. +- A local link in a section must resolve, from the target, to a file in the + checkout being written; user targets accept no local links. +- A target that no longer receives sections is deleted only while it equals its + locked rendering. + +### Fixed + +- Doctor's Codex size check counts only the project chain, as Codex does: the + user file is loaded separately without a limit, separators are not counted, + whitespace-only files add nothing, fallback names apply in every directory, + and an existing `AGENTS.override.md`, even an empty one, hides `AGENTS.md`. + ## 0.1.2 - 2026-10-25 ### Added diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 1e4c2a2..29c2696 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -5,30 +5,54 @@ `InstructionOperations` connects them to `AgentsCore` state, source cache and transactions. Consumers own command parsing, presentation and confirmation. -## Sources and Selection +## Instructions Files + +`Instructions.validateSource` accepts one file format. The file starts with +front matter between `---` lines: a required `description` and an optional +`paths` list. Front matter is a strict subset of YAML: plain, double-quoted or +single-quoted scalars, and `paths` as a flow list of double-quoted strings or a +block list; unknown or repeated keys are errors. The body, with a leading byte +order mark, line endings and leading and trailing blank lines normalized, starts +with an ATX heading of any level; every other heading is a deeper ATX heading, +and the body does not end inside a code or HTML block. A section's `hash` covers +the original bytes. + +`paths` patterns are project-relative and use `*`, `**` as a whole segment, and +`?`. With patterns, the rendered body gets the line "Applies when working on +files matching `…`." after its first heading. `Instructions.directory(for:)` +returns the longest directory shared by the patterns' literal prefixes; a +pattern without wildcards names a file, so its prefix is that file's directory, +and a pattern that starts with a wildcard yields the project root. -Discovery reads `.md` files directly inside `instructions/` and -`.agents/instructions/`, relative to the source's search `path`. Every unit is -validated by `Instructions.validateSource`. Names are filenames without `.md`; -duplicate names across containers are errors. Nested files are not discovered. +## Sources and Selection +Discovery reads `.md` files below `instructions/` and `.agents/instructions/` +of the source's search `path`, recursively. A name is the container-relative +path without `.md`; each segment uses lowercase letters, digits and hyphens. +Symbolic links, invalid names and a name in both containers are errors. Instructions require Git sources. Local sources identify the repository root; use `path` to move its search root. Discovery reads committed trees even when -the working tree is dirty. Each section and prompt section has its own revision, -path and original-byte hash. Source instruction directories cannot be targets. +the working tree is dirty. Each section and prompt section has its own +revision, path and original-byte hash. Source containers cannot hold targets. + +A project's own files live in `.agent/instructions/` and are referenced by bare +name; `alias:name` references a declared source. Own files are read from the +working tree as it is. Their lock records have source `.`, the project-relative +path and the hash, and no revision. Restoring a lock fails when an own file's +hash changed; update reads the current file. `add(InstructionAddOptions, beforeApply:)` accepts a source alias or string, -optional alias, requirement, search path, ordered names and recipients. With -several units and neither names nor `all`, it returns the units without changing -the scope, including its cache and lock files. This selection discovery takes the -read path and stops if recovery is pending. `listOnly` always uses that path. -A single discovered unit is selected automatically by its normalized source ID -and exact section name, separately from user-entered names. Writer-lock rediscovery -must match that identity or fail with an error asking the caller to retry. Content -and pins can refresh for the same identity. Explicit names and `all` -enter the writer path directly. Explicit order is preserved; -`all` adds current units in name order. Add preserves unrelated section and -skill pins. Source aliases remain shared across kinds. +or `.` for own files, plus an optional alias, requirement, search path, ordered +names and recipients. With several units and neither names nor `all`, it +returns the units without changing the scope, including its cache and lock +files. This selection discovery takes the read path and stops if recovery is +pending. `listOnly` always uses that path. A single discovered unit is selected +automatically by its normalized source ID and exact name, separately from +user-entered names. Writer-lock rediscovery must match that identity or fail +with an error asking the caller to retry. Explicit names and `all` enter the +writer path directly. Explicit order is preserved; `all` adds current units in +name order. Add preserves unrelated section and skill pins. Source aliases +remain shared across kinds. ## Targets @@ -40,36 +64,63 @@ skill pins. Source aliases remain shared across kinds. | OpenCode | `$XDG_CONFIG_HOME/opencode/AGENTS.md`, default `~/.config/opencode/AGENTS.md` | `AGENTS.md` | | Gemini CLI | `~/.gemini/GEMINI.md` | `GEMINI.md` | -Locations come from `RuntimeEnvironment`. Selected agents receive the same -ordered sections. Agents sharing a physical file share one lock entry and one -replacement. Project keys are relative to the project root; user keys are -`~/`-relative to the supplied home. Configured user locations outside home use -absolute keys. Locked destinations must remain registered instruction locations -in the runtime environment; lock contents cannot authorize arbitrary writes. +Every target is generated in full by `Instructions.render`: the notice line +`Instructions.notice`, a blank line, and the sections in declared order +separated by one blank line, ending with a newline. Rendering rejects two +sections whose first headings share level and whitespace-collapsed text, and +parses the result to confirm that every section's first heading is still a +document heading. + +In project scope, sections are grouped by `directory`: each group renders into +the `AGENTS.md`, or `GEMINI.md`, of that directory, which must already exist. +User scope renders all sections into each recipient's file. Project keys are +relative to the project root, and a nested key names `AGENTS.md` or `GEMINI.md` +in a directory outside `.git` and `.agent`; user keys are `~/`-relative to the +supplied home, and configured user locations outside home use absolute keys. +Locked destinations must remain registered instruction locations in the +runtime environment; lock contents cannot authorize arbitrary writes. Configured user containers may resolve through symlinks. Journal validation opens project descendants without following links. +A file is owned when the lock records it or `Instructions.isGenerated` finds the +notice on its first line. A planned write over an existing file that is not +owned marks the change `foreign`; add, update apply and combined apply stop with +`InstructionError.unownedTargets` unless `replace` is set. A locked target that +no longer receives sections is deleted while its bytes equal the locked +rendering and kept otherwise. Unit targets lock `headingOffset: 0`, +`created: false` and the rendered file's hash as `blockHash`. + +Links in a rendered target are checked by `Instructions.localLinks`: links, +images, autolinks and reference definitions outside code with a destination +that is relative, absolute or a `file:` URL, and raw HTML `href` and `src` +attributes. A local destination must resolve, from the target file, to an +existing regular file inside the checkout being written and outside any nested +repository or worktree; user targets accept no local destination. Problems stop +the operation with `InstructionError.invalidLinks`. + A root `CLAUDE.md` symlink to `AGENTS.md` needs no write, including before `AGENTS.md` exists. A recognized standalone import in any project Claude file -also suffices. Otherwise the first existing file in `CLAUDE.md`, -`.claude/CLAUDE.md`, `CLAUDE.local.md` order receives a managed import block: -`@AGENTS.md` or `@../AGENTS.md`, relative to its containing file. No project -Claude file means automatic forwarding. Ancestor files are reported and never -modified. +also suffices. Otherwise, when the root `AGENTS.md` is a target, the first +existing file in `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md` order +receives a managed import block: `@AGENTS.md` or `@../AGENTS.md`, relative to +its containing file. No project Claude file means automatic forwarding. +Ancestor files are reported and never modified. ## Operations and Mutation Contract | Consumer operation | Behavior | | --- | --- | -| `list(source:scope:environment:)` | Inspect committed, validated units | +| `list(source:scope:environment:)` | Inspect committed, validated files of a source | +| `listOwn(environment:)` | Inspect the project's own files in the working tree | | `listManaged(scope:environment:)` | Return locked sections, prompts and targets, including missing targets | -| `updateInstalled(..., apply:beforeApply:)` | Resolve the declaration and preview or apply all targets together | -| `installResolvedReport(scope:environment:)` | Restore locked pins, targets and offsets without changing state bytes | +| `updateInstalled(..., apply:replace:beforeApply:)` | Resolve the declaration and preview or apply all targets together | +| `installResolvedReport(scope:environment:)` | Restore locked renderings without changing state bytes | | `remove(names:scope:agents:environment:beforeApply:)` | Remove sections from file and prompt selections and lock records | | `renderChatGPT(prompt:scope:environment:)` | Return locked sections followed by the prompt's current custom file | -| `initializeInstructions(named:directory:)` | Create a validated `.md`, refusing an existing entry | +| `initializeInstructions(named:directory:)` | Create a validated `.md` with front matter, refusing an existing entry | | `doctor(scope:environment:codexConfiguration:)` | Inspect one scope and compare sections against the other scope | | `doctor(projectRoots:environment:codexConfiguration:)` | Audit explicit project roots without writing | +| `export(projectRoots:environment:)` | Map the user scope's and each root's locked targets to their sections without writing | An `agents` argument sets the complete instruction recipient list. Removing names accepts `alias:name` references or unambiguous bare names and removes @@ -77,8 +128,8 @@ those sections from prompts as well. Empty prompts are removed. Other source declarations and skill records remain available to their owners. Planning validates required content before applying. Reports include old and -new section records, target before/after bytes and recipients, drift, custom-section -adoptions and conflicts, block differences, missing-lock status and changed prompt names. +new section records, target before/after bytes and recipients, drift, foreign +targets, a missing-lock status and changed prompt names. `InstructionTargetChange.beforeAgents` is nil when the previous lock has no target entry; `afterAgents` is empty when the target is no longer managed. Both recipient arrays are sorted by agent raw value. `agentsChanged` compares those recipients, @@ -95,17 +146,16 @@ bytes/presence, target ancestry and all Claude forwarding decision inputs before and after retention. `InstructionUpdatePlan` supplies package-visible planning, validation, retention and staging to both standalone updates and `AgentsUpdates`; the latter commits both kinds together as described in -[Updates](Updates.md). Add throws conflict differences -unless `replace` is enabled. Update previews conflicts and applies newly resolved -content. Install restores drift but stops on a conflicting custom section. +[Updates](Updates.md). Mutations hold the scope writer lock and use the durable journal for instruction files, forwarding files, declaration, lock and cache pruning. Exact source materializations are verified and published through cache transactions before the target/state transaction. The journal has fixed project instruction paths, -configured user instruction roots and an authoring root restricted to named -Markdown files. Initialization uses a project state lock and journal in the -supplied directory without creating a declaration or resolved file. +nested project `AGENTS.md` and `GEMINI.md` paths, configured user instruction +roots and an authoring root restricted to named Markdown files. Initialization +uses a project state lock and journal in the supplied directory without +creating a declaration or resolved file. Read operations take an existing shared scope lock without creating one or replaying recovery. Pending recovery stops listings and previews. Doctor reports @@ -115,17 +165,15 @@ from that scope. A pending other scope suppresses cross-scope comparisons while the current scope can still be audited. A mutating state operation recovers the transaction and asks the caller to retry. Source inspection and update preview may fetch mirror objects and use disposable snapshots, but never -publish materializations, declaration, lock or targets. Doctor reads remote ref -advertisements but does not fetch objects or create files, including in projects -with no state directory. - -Install reconstructs and verifies locked blocks before replacement, using -recorded heading offsets even if custom titles changed. Update recomputes -offsets. Removing the last section removes its block and deletes a file only -when its previous lock says `created: true` and no custom content remains. -Without a lock entry a file is never deleted. Lost-lock update reports the -comparison; apply adopts identical blocks or replaces differing content and -records existing files as `created: false`. +publish materializations, declaration, lock or targets. Doctor and export read +remote ref advertisements at most and do not fetch objects or create files, +including in projects with no state directory. + +Install renders the locked sections, verifies every rendering against its +locked hash before replacement, and restores drifted files. Lost-lock update +reports the comparison; apply keeps identical files, replaces differing +generated files, takes over others only with `replace`, and records targets as +`created: false`. Without a lock entry a file is never deleted. ## ChatGPT Prompts @@ -136,14 +184,16 @@ revision change with identical section hashes alone does not mark a prompt changed. Append files remain live owner content; their independent edits do not require a lock update. -Render verifies locked hashes, keeps source heading levels, omits markers and -appends the custom file's bytes. It fails without locked sections or if an append -path escapes the scope through a symlink. It never writes to ChatGPT. +Render verifies locked hashes, renders sections as in targets without the +notice, and appends the custom file's bytes. It fails without locked sections or +if an append path escapes the scope through a symlink. It never writes to +ChatGPT. ## Diagnostics -Doctor reports missing or drifted blocks, malformed targets, missing locks, -custom-section adoptions and conflicts using cached locked content, duplicate +Doctor reports missing targets, drifted targets, files in target locations that +agents did not generate, own files changed since the lock, links in the locked +renderings that no longer resolve, invalid targets, missing locks, duplicate source-qualified sections across scopes, Claude forwarding and ancestor problems, and uncommitted selected local source paths. Git status uses `--no-optional-locks` to avoid index refresh writes. File and ChatGPT prompt pins @@ -162,15 +212,21 @@ a cached commit or an advertised branch head; otherwise inspection reports an unresolved source. Doctor does not fetch to resolve missing objects or validate upstream content. -Codex checks report a nonempty `AGENTS.override.md` hiding managed content and -sum loaded instruction bytes and separators along the global and -root-to-project chain, honoring `project_root_markers` (default `.git`) and -`project_doc_fallback_filenames`. With no root marker, only the project directory -is checked. Consumers supply `CodexInstructionConfiguration` with the effective -byte limit, fallback filenames and root markers after resolving Codex trust, -profiles and policy. Multi-root audit accepts a configuration resolver per root. -The TOML initializer can merge trusted layers in precedence order, preserving -omitted settings; trust decisions and layer selection belong to the consumer. +Codex checks follow how Codex loads instructions. The user file is loaded +separately without a size limit; a non-blank `AGENTS.override.md` beside it +hides a managed user file. In project scope, each chain runs from the nearest +directory with a `project_root_markers` entry (default `.git`), or only the +directory itself without one, down to the project directory and to each +directory holding a generated `AGENTS.md`. In every directory of a chain, the +first regular file among `AGENTS.override.md`, `AGENTS.md` and +`project_doc_fallback_filenames` is loaded, even when empty, so an existing +override hides a managed `AGENTS.md`. A chain's budget counts loaded file bytes, +skips whitespace-only files and adds no separators. Consumers supply +`CodexInstructionConfiguration` with the effective byte limit, fallback filenames +and root markers after resolving Codex trust, profiles and policy. Multi-root +audit accepts a configuration resolver per root. The TOML initializer can merge +trusted layers in precedence order, preserving omitted settings; trust decisions +and layer selection belong to the consumer. Trusted `.codex/config.toml` layers override user settings, with the closest to the working directory taking precedence, following [Codex configuration rules](https://learn.chatgpt.com/docs/config-file/config-advanced). @@ -179,6 +235,6 @@ defaulting to 32 KiB. Table fields and multiline string contents cannot override it; invalid budgets produce a diagnostic. Discovery follows the [Codex instruction guide](https://developers.openai.com/codex/guides/agents-md). -Multi-root audit deduplicates explicit roots, reports unavailable or pending -scopes without repairing them, and continues with other roots. It never -searches the user's filesystem for projects. +Multi-root audit and export deduplicate explicit roots, report unavailable or +pending scopes without repairing them, and continue with other roots. They never +search the user's filesystem for projects. diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index bc3ef6a..36539c0 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -189,75 +189,45 @@ workflows. It composes the text APIs below with scope state and journaled writes See [Instruction lifecycle](Instructions.md) for consumer APIs, target mapping, lost-lock recovery and diagnostics. -`Instructions` validates source bytes into immutable `InstructionSection` -values, assembles or removes managed blocks, detects drift, renders ChatGPT -prompts, and compares source-qualified identities across scopes. The `Markdown` -product from [swift-markdown](https://github.com/swiftlang/swift-markdown) -provides CommonMark structure, semantic inline text, and block line ranges through cmark-gfm. -Only `AgentsInstructions` depends on that product. The adapter retains original -line bytes for splicing; it does not format the parsed tree. - -Only top-level headings are target titles or section boundaries. Headings -inside lists and block quotes belong to their containing section. Every source -heading, including container headings, shifts by the target offset and is -checked for level-6 overflow. A source starts with a top-level ATX H1, has no -other H1 anywhere, uses no Setext headings, and cannot end inside a code or HTML -block. Heading identity is the AST heading's `plainText`, trimmed with whitespace -collapsed. Emphasis delimiters and link destinations are absent, entities are -decoded, and code spans retain the backticks supplied by `plainText`. This same -identity controls matching, title detection, and duplicate selection checks; -rendering retains the original source syntax. -Markers count only as top-level, single-line HTML blocks whose complete source -line equals the fixed marker text; indented, quoted, or padded examples are not -markers. - -The parser supplies heading levels, start lines, and container ownership. -Splicing uses physical line boundaries. The adapter verifies ATX syntax on the -start line: one through six hashes followed by a space, tab, or end of line, -with at most three leading spaces at the top level. Within AST-confirmed -containers, a small prefix scan locates the opening run after list and quote -prefixes. A top-level Setext span starts after any leading link reference -definitions consumed from its paragraph block. Because those definitions have -no AST nodes, the adapter reparses original physical prefixes and identifies -complete definition-only prefixes by their empty document trees. This also -handles multiline labels, destinations, and titles. Definition lines remain -custom bytes and are excluded from section comparisons and replacement ranges, -including when a selected parent section contains the Setext heading. -A top-level Setext span ends at a physically verified underline: -up to three leading spaces, a nonempty run of the appropriate `=` or `-`, and -optional trailing spaces or tabs. Inline source coordinates are not physical -positions and are never used to slice target bytes. Setext end coordinates are -also unsuitable because they can extend into the next block. Prefix verification -is limited to Setext paragraph blocks that could begin with a reference -definition; CommonMark remains responsible for recognizing the definitions. +`Instructions` validates instructions files into immutable `InstructionSection` +values, renders generated targets and ChatGPT prompts, recognizes generated +files by their notice, finds local links, detects drift of Claude import blocks, +and compares source-qualified identities across scopes. The `Markdown` product +from [swift-markdown](https://github.com/swiftlang/swift-markdown) provides +CommonMark structure, semantic inline text, and block line ranges through +cmark-gfm. Only `AgentsInstructions` depends on that product. The adapter +retains original line bytes; it does not format the parsed tree. + +`InstructionFrontMatter` reads the fixed front matter, a strict YAML subset with +a required `description` and optional `paths`. The body keeps its source syntax: +it starts with a top-level ATX heading of any level, every other heading, +including container headings, is a deeper ATX heading, and it cannot end inside +a code or HTML block. Heading identity is the AST heading's `plainText`, trimmed +with whitespace collapsed, plus its level; it controls duplicate checks within a +target. Rendering inserts the `paths` line after the first heading and never +changes heading levels. A rendered target is reparsed, and every section's first +heading must remain a document heading. Because the AST does not expose fence or HTML closure state, source validation reparses a continuation token in the terminal block's container and checks whether it becomes code or HTML. Physical list prefixes become continuation indentation and quote prefixes remain intact. The token is never emitted. -Final assembly is reparsed and must contain exactly the expected managed block. -A leading UTF-8 BOM is kept separately as file metadata before parsing. Target -assembly and removal restore those bytes at the start, including when the block -is prepended or no custom content remains. The BOM does not count as custom -content or enter the managed block hash. Source hashes include it, while source +Link inspection walks the AST for links, images and raw HTML outside code, and +reads reference definitions, which have no AST nodes, from lines outside code +blocks. It reports destinations that are relative, absolute or `file:` URLs, +decoded and without query or fragment; lifecycle callers resolve them against +the checkout being written. + +A leading UTF-8 BOM in a source is metadata: source hashes include it, while rendering omits it. ChatGPT custom content is UTF-8 validated and appended as -original bytes, including any BOM and line endings. - -Selected headings are grouped once. Target headings and section boundaries -are indexed in one traversal, with a reverse pass across the six heading -levels. Removal ranges are sorted and applied in a single pass over target -lines; assembly does not scan all headings for each selected section. - -Assembly returns bytes, heading offset, the rendered block and its hash, -adoptions, conflicts, a block difference, and whether custom content remains. -The caller chooses whether to replace conflicting custom sections and supplies -the locked heading offset for installation. Existing managed content is -rendered anew; lifecycle callers check drift before deciding to persist it. -Source hashes cover original bytes. Block hashes cover LF-normalized marker -and content lines, including the final LF. Drift detection accepts an optional -reconstructed locked block for a textual difference; a hash alone establishes -drift but cannot recover the old text. +original bytes, including any BOM and line endings. Source hashes cover +original bytes; a target's hash covers its rendered bytes. + +Markers count only as top-level, single-line HTML blocks whose complete source +line equals the fixed marker text; indented, quoted, or padded examples are not +markers. They delimit only the managed import block in a project Claude file, +whose hash covers LF-normalized marker and content lines. `ClaudeForwarding` renders import blocks and classifies existing project Claude files from caller-supplied bytes and symbolic-link metadata. Forwarding requires diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 8b047e8..2a60814 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -77,9 +77,11 @@ Restoration reads these recorded URLs or verified digest cache entries and never reads an index. Missing pins or mismatched content stop restoration. Instruction section records carry name, source, revision or artifact, path and -hash. Prompts hold ordered locked sections and optional append paths. Physical -targets record agents, heading offset or import, block hash, and whether the -file was created by the tool. Skill writes retain these records unchanged. +hash; a project's own files use source `.`, their project-relative path and hash, +and no revision. Prompts hold ordered locked sections and optional append paths. +Physical targets record agents, heading offset 0 or import, the hash of the +generated file or import block, and `created`, which unit targets always record +as false. Skill writes retain these records unchanged. Instruction lifecycle writes preserve skill records. Target keys are project relative or user-home relative; configured user files outside home use absolute keys checked against the runtime's registered instruction locations. diff --git a/Documentation/Architecture/Watch.md b/Documentation/Architecture/Watch.md index 2416fab..8514dd4 100644 --- a/Documentation/Architecture/Watch.md +++ b/Documentation/Architecture/Watch.md @@ -39,8 +39,9 @@ Unchanged items are omitted. A name can exist in both skills and instructions; the optional kind filter disambiguates it. Git comparisons discover skills in disposable snapshots through the supplied -discovery function. Instruction units are Markdown files directly inside -`instructions/` or `.agents/instructions/`, named by their filename stem. +discovery function. Instruction units are Markdown files below +`instructions/` or `.agents/instructions/`, subdirectories included, named by +their container-relative path without `.md`. The declared search path applies to both. Duplicate instruction names are an error. Watch compares source bytes without validating, rendering or installing instruction sections. Uncommitted working-tree content is ignored. diff --git a/Documentation/Proposals/AgentInstructions.md b/Documentation/Proposals/AgentInstructions.md index 5dc8e0c..8ac8aa6 100644 --- a/Documentation/Proposals/AgentInstructions.md +++ b/Documentation/Proposals/AgentInstructions.md @@ -34,8 +34,11 @@ The skill implementation this package starts from has related gaps: - Manage skills and instructions as two kinds of one model: shared sources, declaration, lock and lifecycle commands. -- Make every managed instruction section traceable to a source and a locked - version, keep owner-written content editable, and make drift detectable. +- Write each piece of guidance once, as an instructions file, and generate + every target from them; make every target traceable to its sections and + their locked versions, and make drift detectable. +- Scope a section to the files it governs, with the same effect in every agent + that reads the generated files. - Render instructions as named prompts for ChatGPT project instructions and scheduled tasks. - Restore exactly what the lock records; re-resolve only on `add` and `update`. @@ -45,8 +48,8 @@ The skill implementation this package starts from has related gaps: - Agent runtime configuration such as MCP servers, hooks, subagents and settings. These are evaluated separately after instructions ship. -- Collaboration. The tool is the only writer of managed sections; a change to a - managed section from anywhere else is drift. +- Collaboration. The tool is the only writer of generated targets; a change to + a target from anywhere else is drift. - Version control. The tool writes files; each project decides whether and when to commit them. - Compatibility with earlier state files and source syntax. @@ -70,11 +73,9 @@ writes the same declaration, lock and watch state and leaves the | --- | --- | | Source | A Git repository, a local directory or a well-known index that provides skills, instructions or both | | Skill | A directory with a `SKILL.md`, loaded by agents on demand | -| Instructions | One Markdown file in a source, loaded by agents in every session | -| Section | The content of one instructions file as written into a target | -| Target | A file that agents read instructions from, or a named ChatGPT prompt | -| Managed block | The part of a target file that the tool writes from sources | -| Custom content | Everything in a target outside the managed block; it belongs to the target's owner | +| Instructions | One self-contained Markdown file in an instructions container, loaded by agents once it is written into a target | +| Section | The body of one instructions file as written into a target | +| Target | A file that agents read instructions from, generated in full from sections, or a named ChatGPT prompt | | Declaration | What the user wants: sources, selected skills and sections, agents, subscriptions | | Lock | What was resolved and written: pins, content hashes, installs and targets | | Pin | The immutable state an item was resolved at: a Git revision, or a well-known artifact's URL and digest | @@ -91,19 +92,51 @@ containers (`skills/` with `.curated`, `.experimental` and `.system`, directories named by plugin and marketplace manifests, and a recursive search when these find nothing or when `--full-depth` is given. -Instructions are `.md` files directly under `instructions/` or -`.agents/instructions/`. The file name without `.md` is the instructions name. -An instructions file starts with exactly one level-1 ATX heading and uses -level 2 or deeper for everything else: +Instructions are `.md` files in the `instructions/` and `.agents/instructions/` +containers, including their subdirectories. An instructions file's name is its +path inside the container without `.md`, such as `epd/review` for +`instructions/epd/review.md`. Each path segment uses lowercase letters, digits +and hyphens, so names stay distinct on case-insensitive file systems. A name +present in both containers is an error. The containers hold regular files only; +a symbolic link is an error, not a way to publish a file kept elsewhere. Every +file in a container is an instructions file; other documents in the source +refer to them. + +A project's own instructions live in its `.agent/instructions/` and are +selected by bare name. They are read from the working tree as it is, like a +skill in `edit` mode, so a changed instructions file and the target it +regenerates belong to one commit; the lock records their hashes. + +An instructions file has a fixed format: ```markdown -# Canonical Artifacts +--- +description: Flag claims that the code and tests do not support. +paths: ["Sources/**/*.swift"] +--- +## Code Review Rules -Treat conversation, review feedback, and intermediate attempts as editing -context. ... +### Claims + +- Flag README, DocC, or release-note statements ... ``` -A source's instructions directory is never itself a target location. +- Front matter is required. `description`, also required, is one sentence on + what the file makes the agent do; `list` shows it. `paths` is an optional list + of project-relative glob patterns using `*`, `**` and `?`. Other keys are + errors. Front matter is not written into targets. +- The body starts with one ATX heading at the level the author wants it to + have in the target; every other heading is a deeper ATX heading. The tool + never changes heading levels. +- The body does not end inside a code or HTML block. +- A link to a local file must resolve, from the target file, to a regular file + inside the checkout being written. User targets belong to no checkout, so + their sections link to no local file. URLs with a scheme other than `file:` + and bare fragments are unrestricted; raw HTML links are invalid. Text that + names a file, such as "run the checks in `CONTRIBUTING.md`", refers to the + target's own files. + +A source's instructions container is never itself a target location. | Source kind | Pinned by | Notes | | --- | --- | --- | @@ -125,12 +158,16 @@ Two declared sources that normalize to the same ID are an error. | Scope | Declaration | Lock | Watch state | Targets | | --- | --- | --- | --- | --- | -| Project | `.agent/agents.json` | `.agent/agents.resolved` | `.agent/agents.watch` | Project skills; `AGENTS.md`, `GEMINI.md` and Claude forwarding at the project root; ChatGPT prompts | +| Project | `.agent/agents.json` | `.agent/agents.resolved` | `.agent/agents.watch` | Project skills; `AGENTS.md` and `GEMINI.md` at the project root and in directories named by `paths`; Claude forwarding; ChatGPT prompts | | User | `~/.agents/agents.json` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | User skills; each agent's user instructions file; ChatGPT prompts | -All three files are local state and are not committed. The project's state -lives inside the project, so moving a repository moves its state. User state is -always under `~/.agents`. +A project commits its declaration and lock, with its instructions files and +generated targets, as it would a package manifest and its lock: every checkout, +worktree and clone then holds the recipe and the result. The watch state, the +source cache and installed skill links are local and ignored. A project that +commits its state declares only portable sources, Git URLs or its own +instructions; a local source records an absolute path. User state is local and +always lives under `~/.agents`. ### Declaration @@ -155,7 +192,7 @@ Commands edit the declaration; editing it by hand is possible. }, "instructions": { "agents": ["codex", "claude-code", "cursor", "opencode"], - "sections": ["rules:canonical-artifacts", "rules:first-principles-work"], + "sections": ["guide", "rules:canonical-artifacts", "code-review-rules"], "chatgpt": { "training": { "sections": ["rules:canonical-artifacts", "rules:training-logging"], @@ -187,6 +224,8 @@ Commands edit the declaration; editing it by hand is possible. instruction file of every listed agent. Every change to the list or its pins is applied to all listed targets together; `--agent` on instruction commands sets the list of recipients. +- A section reference is `alias:name` for a declared source, or a bare name for + the project's own instructions. - `chatgpt` names prompts for ChatGPT project instructions and scheduled tasks. Each prompt has its own ordered section list and an optional custom-content file, relative to the scope root, that `render` appends. @@ -243,6 +282,12 @@ Commands edit the declaration; editing it by hand is possible. }, "instructions": { "sections": [ + { + "name": "guide", + "source": ".", + "path": ".agent/instructions/guide.md", + "hash": "sha256:…" + }, { "name": "canonical-artifacts", "source": "local:/Users/me/Developer/rules", @@ -251,10 +296,9 @@ Commands edit the declaration; editing it by hand is possible. "hash": "sha256:…" }, { - "name": "first-principles-work", - "source": "local:/Users/me/Developer/rules", - "revision": "a03a475f0c1d2e3b4a5968778695a4b3c2d1e0f9", - "path": "instructions/first-principles-work.md", + "name": "code-review-rules", + "source": ".", + "path": ".agent/instructions/code-review-rules.md", "hash": "sha256:…" } ], @@ -274,7 +318,7 @@ Commands edit the declaration; editing it by hand is possible. "targets": { "AGENTS.md": { "agents": ["codex", "claude-code", "cursor", "opencode"], - "headingOffset": 1, + "headingOffset": 0, "blockHash": "sha256:…", "created": false }, @@ -299,11 +343,16 @@ Commands edit the declaration; editing it by hand is possible. links to the source directory and carry no pin or hash. - Instruction targets are keyed by physical file: a path relative to the project root, or a `~`-relative path in user scope. Agents share an entry - only when their files resolve to the same path. `created` records that the - tool created the file. -- `install` uses the lock and nothing else: each install's agent and mode, - each pin and each target's heading offset. A pin that cannot be fetched, or - content whose digest does not match, is an error, never a substitution. + only when their files resolve to the same path. For a generated target, + `blockHash` covers the whole rendered file, `headingOffset` is always 0 and + `created` is false; ownership is proven by the file's generated notice, and + which sections a target receives follows from their `paths`. +- A project's own instructions are recorded with source `.`, their path in the + project and their hash; they have no revision, because they are read live. +- `install` uses the lock and nothing else: each install's agent and mode, and + each pin. A pin that cannot be fetched, content whose digest does not match, + or an own instructions file whose hash changed since the lock is an error, + never a substitution. - Output is sorted, except section order, and has no timestamps. Writes take a file lock and replace the file atomically. @@ -344,11 +393,12 @@ agents │ ├── update [names…] [--apply] │ └── init [name] ├── instructions -│ ├── add [names…] [--replace] +│ ├── add [names…] `.` selects the project's own; [--replace] │ ├── list [source] │ ├── remove -│ ├── update [--apply] +│ ├── update [--apply] [--replace] │ ├── render chatgpt +│ ├── export [--root …] │ └── init ├── watch │ ├── add @@ -364,18 +414,21 @@ agents `--agent `, `--scope project|user` and `--path ` mean the same in every command except `install`. `--agent` defaults to the declaration's `agents`. `skills add` also takes `--mode link|copy|edit`, and `skills add` and -`skills list ` take `--full-depth`. +`skills list ` take `--full-depth`. `instructions add` and +`instructions update --apply` take `--replace` to take over an existing target +file that agents did not generate. For skills, omitting `--agent` makes `remove` act on all recipients and `list` show all recipients; declaration defaults apply only when adding or when a selection has no recipients. | Command | Behavior | | --- | --- | | `add` | Update the declaration, resolve, write, update the lock. Any stop leaves the declaration, lock and files unchanged | -| `update` | Re-resolve the declaration and show what would change against the files on disk. `--apply` writes the resolved content and the new lock together, showing the difference before it replaces drifted or conflicting content. Without names it reconciles `"all"` selections with the source's membership; with names it touches only those skills, and a named skill missing upstream is an error. `--apply` lists the ChatGPT prompts whose content changed, since ChatGPT has to be updated by pasting the new render | -| `install` | Restore skills and managed blocks exactly as the lock records them, without resolving. It takes no `--agent` or `--mode` | +| `update` | Re-resolve the declaration and show what would change against the files on disk. `--apply` writes the resolved content and the new lock together, showing the difference before it replaces drifted content. Without names it reconciles `"all"` selections with the source's membership; with names it touches only those skills, and a named skill missing upstream is an error. `--apply` lists the ChatGPT prompts whose content changed, since ChatGPT has to be updated by pasting the new render | +| `install` | Restore skills and instruction targets exactly as the lock records them, without resolving. It takes no `--agent` or `--mode` | | `list` | Installed skills, or managed sections and targets; with a source, what it provides | | `remove` | Remove from the declaration, files and lock | | `init` | Create a skill directory or an instructions file in the current directory | | `render` | Print a ChatGPT prompt: its locked sections followed by its custom-content file, without markers. A prompt without locked sections is an error | +| `export` | Print the instruction mapping assembled from the user lock and the locks of the projects given with `--root`: for each target, its scope, recipients and sections with their sources and pins. It describes the locked state, not what is on disk, and reports a missing or unreadable scope instead of omitting it | | `watch add` | Subscribe and record the source's current revision as seen | | `watch status` | Report each subscribed source since its seen revision, per skill and instructions: new, changed, removed | | `watch diff` | Show the changes behind `status`, for one source or one item | @@ -383,16 +436,26 @@ For skills, omitting `--agent` makes `remove` act on all recipients and `list` s | `watch remove` | Drop the subscription and its state; installed items stay | | `doctor` | Compare lock and disk and report problems (see below). `--root` audits several projects read-only, given explicit directories | -`update` without `--apply`, `list`, `doctor`, `render`, `watch status` and -`watch diff` change no declaration, lock, watch state, target or checked-out -revision. They may fetch new objects into a source mirror. - -`doctor` reports missing installs, drifted skill copies, drifted managed -blocks, sources with newer matching versions, local sources with uncommitted -changes in selected paths, sections installed at both scopes, Claude Code -forwarding problems, a Codex `AGENTS.override.md` that hides a managed -`AGENTS.md`, and Codex instructions that exceed `project_doc_max_bytes` (Codex -configuration, default 32 KiB) for the combined files Codex loads. +`update` without `--apply`, `list`, `doctor`, `render`, `export`, +`watch status` and `watch diff` change no declaration, lock, watch state, +target or checked-out revision. They may fetch new objects into a source +mirror. + +`doctor` reports missing installs, drifted skill copies, missing or drifted +targets, existing files in target locations that agents did not generate, own +instructions changed since the lock, invalid instructions files and links, +sources with newer matching versions, local sources with uncommitted changes in +selected paths, sections installed at both scopes, Claude Code forwarding +problems, and a Codex `AGENTS.override.md` that hides a managed `AGENTS.md`. + +It also reports a project whose Codex instructions exceed +`project_doc_max_bytes` (Codex configuration, default 32 KiB). The budget +covers only the project chain: from the project root, found by +`project_root_markers`, down to the working directory, the first regular file +in each directory among `AGENTS.override.md`, `AGENTS.md` and the configured +fallback names, even an empty one. It counts file bytes, not the separators +Codex inserts, and skips whitespace-only files. The user file +`$CODEX_HOME/AGENTS.md` is loaded separately and has no size limit. The `skill` executable exposes the skills and watch subset with the same behavior: `skill add|list|remove|update|init|install|doctor|watch …`. @@ -415,8 +478,11 @@ above it. When `claude-code` is a target in project scope: - a project `CLAUDE.md` that is a symbolic link to `AGENTS.md` already forwards, and nothing is written; - otherwise, when the project has `CLAUDE.md`, `.claude/CLAUDE.md` or - `CLAUDE.local.md`, the tool writes a managed block containing an import of - the project's `AGENTS.md` into the first of them that exists, with the path + `CLAUDE.local.md`, the tool writes a managed block, the lines between + `` and ``, containing + an import of the project's root `AGENTS.md` into the first of them that + exists, with the path relative to that file (`@AGENTS.md`, or `@../AGENTS.md` in `.claude/CLAUDE.md`). An existing import of the project's `AGENTS.md`, resolved relative to the containing file, counts as forwarding only as the tool's @@ -429,86 +495,66 @@ above it. When `claude-code` is a target in project scope: ## Writing Targets -A file target consists of custom content and at most one managed block: +Every target is generated in full. The tool owns the whole file; nothing in it +is written by hand, and changes are made in the instructions files: ```markdown -# Example Agent Guide + - -## Canonical Artifacts - -... +# Example Agent Guide -## First-Principles Work +Read `README.md` first. -... - +## Code Review Rules -## Task Route +### Claims -... +- Flag README, DocC, or release-note statements ... ``` -Markdown structure follows CommonMark: headings and marker lines are -recognized only outside fenced and indented code blocks. Source files must use -ATX headings and must not end inside a code block; targets may also contain -Setext headings. The assembled file is parsed before it is written and must -contain exactly the expected block; otherwise nothing is written. - -1. A section is a heading and everything up to the next heading of the same or - higher level, the next marker line or the end of the file. Sections in the block - appear in declared order and are identified by heading. -2. The block is one contiguous region from the BEGIN line to the END line. - Their text is fixed and carries no versions. More than one block, or - unpaired or nested markers, is an error and nothing is written. -3. The target's title is the first level-1 heading in custom content before the - block that does not match the level-1 heading of a selected section. With a - title, every heading in the block is shifted one level down; - a shift beyond level 6 is an error. The offset is computed on the first - write and on `update` when the title appears or disappears; `install` uses - the locked offset. -4. An existing section in custom content matches a declared section when its - level and heading text equal those of the shifted source section, after - trimming and collapsing whitespace. Several matches for one declared - section, or two selected sections with the same heading from any sources, - are an error. -5. On the first write the block goes where the earliest matching section is, - otherwise before the first heading after the title, otherwise at the end - of a file with a title, otherwise at the start. -6. A matching section with identical content is adopted: it moves into the - block. A matching section with different content stops `add` with the - difference unless `--replace` is given and is replaced by `update --apply` - after the difference is shown. `update` and `doctor` only report adoptions - and conflicts; `install` stops on a conflict. -7. The tool owns the marker lines, the block content and one blank line - between the block and adjacent custom content. Custom content keeps its - bytes. Section content is the source file with LF line endings, trailing - blank lines removed and headings shifted; sections are separated by one - blank line. When the block ends the file, the file ends with one newline. - Removing the block leaves the custom content ending with one newline. -8. A section's `hash` covers the source file bytes. `blockHash` covers the - rendered block from the BEGIN line through the END line with LF endings. - Any difference from `blockHash` is drift: `doctor` reports it, `install` - restores the locked content, and `update --apply` writes the newly resolved - content after showing the difference. -9. Writing the same lock into the same custom content produces identical - bytes. -10. Removing the last section removes the block, its markers and its - separating blank line. A file whose lock entry records `created` and that - has no custom content left is deleted; any other file is kept. -11. A section installed at both user and project scope produces a `doctor` - warning. +1. A target is the notice line, a blank line, and its sections in declared + order separated by one blank line, ending with one newline. A section is an + instructions file's body with front matter removed, LF line endings and no + leading or trailing blank lines. +2. A section with `paths` gets one line after its first heading, "Applies when + working on files matching `Sources/**/*.swift`.", listing its patterns in + order. In project scope it is written into the `AGENTS.md`, and `GEMINI.md` + for Gemini CLI, of the longest directory that the literal prefixes of all its + patterns share; a pattern that starts with a wildcard keeps the section at + the project root. User targets have no directories, so the line alone scopes + the section. A directory receives a target only when a section is written to + it. +3. Two sections in one target whose first headings have the same level and + whitespace-collapsed text are an error. +4. The assembled target is parsed before it is written. Each section's first + heading must remain a document-level heading, and its links must satisfy + the rules under Sources; otherwise nothing is written. +5. A file is owned when the lock records it as a target or its first line is + the notice. Writing over an existing file that is not owned requires + `--replace`, after its difference is shown; otherwise `add` and + `update --apply` stop and name the file. +6. A section's `hash` covers the instructions file's bytes. `blockHash` covers + the rendered target with LF endings. Any difference between a target and its + locked rendering is drift: `doctor` reports it, `install` restores the + locked rendering, and `update --apply` writes the newly resolved content + after showing the difference. +7. Writing the same lock produces identical bytes. +8. A target that no longer receives sections is deleted when its bytes equal + the locked rendering; a drifted one is kept and reported. A file without a + lock entry is never deleted. +9. A section installed at both user and project scope produces a `doctor` + warning. `agents instructions render chatgpt ` prints the prompt's locked -sections in order with their source headings, followed by its custom-content -file. The output is pasted into ChatGPT, for example with `pbcopy`; the tool -does not write to ChatGPT. +sections in order, rendered as in targets but without the notice, followed by +its custom-content file. The output is pasted into ChatGPT, for example with +`pbcopy`; the tool does not write to ChatGPT. -A lost lock is not restored exactly, because headings do not identify a pin. -`update` re-resolves the declaration and reports how the result compares with -the existing block; `update --apply` adopts identical content, replaces -differing content after showing the difference, and writes the new lock. A file -without a lock entry is never deleted. +A lost lock is not restored exactly. `update` re-resolves the declaration and +compares the result with the files on disk; `update --apply` keeps an +identical file, replaces a differing generated file after showing the +difference, takes over a file agents did not generate only with `--replace`, +and writes the new lock. ## Watch @@ -560,3 +606,41 @@ working tree that another operation depends on. kinds. - Skill inventory, reference graph and directional-reference checks for skill collections. + +## Design References + +- Agents keep persistent instructions as one Markdown file per rule in a + conventional directory: GitHub Copilot's + [`.github/instructions/`](https://docs.github.com/en/copilot/concepts/prompting-and-context/custom-instructions), + Cursor's [`.cursor/rules/`](https://cursor.com/docs/context/rules) and + Claude Code's [`.claude/rules/`](https://code.claude.com/docs/en/memory). + Instructions containers follow the same layout, with front matter as in + Cursor's `.mdc` rules and `paths` as in Claude Code's path-scoped rules. +- [Ruler](https://github.com/intellectronica/ruler) and + [rulesync](https://github.com/dyoshikawa/rulesync) concatenate a rules + directory into each agent's instruction file and replace the whole file. The + tool generates whole files the same way and also: commits the generated files + so that readers that cannot generate them see them; records a lock with + hashes, reports drift and writes through a recoverable transaction instead of + leaving backups; pins shared sources and reports upstream changes; checks + that links resolve where the section lands; validates a fixed file format; + checks Codex's project size budget; audits several projects and exports their + mapping; and renders ChatGPT prompts. +- GitHub Codex code review reads only committed `AGENTS.md` files, the root file + and nested files that cover a changed file, and follows their + `## Code Review Rules` + ([Codex GitHub integration](https://learn.chatgpt.com/docs/third-party/github)). + Generated targets are therefore committed. +- A nested `AGENTS.md` scopes its directory. Claude Code loads one when it + reads a file there ([memory](https://code.claude.com/docs/en/memory)); Codex + loads the chain from the project root to its working directory and instructs + the model to obey every `AGENTS.md` that covers a file it changes + ([`agents_md.rs`](https://github.com/openai/codex/blob/970111f6cb62cc02fe36a82ea7d71b37a2889c97/codex-rs/core/src/agents_md.rs)). + `paths` uses this chain, and its explicit line also scopes user targets, + which have no directories. +- Codex limits only the project chain to `project_doc_max_bytes` and loads the + user file separately, which `doctor` follows. +- Cursor rules mention files of the same project for the agent to read when + needed and keep what must always be in context in the rule body. A section + is written into other projects and user files, so a local link must resolve + where it lands. diff --git a/README.md b/README.md index 3356987..02128f4 100644 --- a/README.md +++ b/README.md @@ -194,33 +194,42 @@ recovery and callback contracts. ### Instructions -`InstructionOperations` manages ordered sections from committed `.md` files -under a source's `instructions/` or `.agents/instructions/` search root: - -- `add(_:)` selects sections and writes every recipient together. Conflicting - custom sections stop the operation unless `replace` is enabled. -- `list(source:...)` inspects a source; `listManaged(...)` returns locked - sections, prompts and physical targets. +An instructions file is one Markdown file in a source's `instructions/` or +`.agents/instructions/` container, subdirectories included, named by its path +there without `.md`. It starts with front matter holding a required +`description` and optional `paths` globs, then a body that begins with one +heading. A project's own files live in `.agent/instructions/` and are selected +by bare name. `InstructionOperations` generates whole target files from them: + +- `add(_:)` selects files and writes every target together; source `.` selects + the project's own files. Writing over a file that agents did not generate + needs `replace`. +- `list(source:...)` and `listOwn(...)` inspect available files; + `listManaged(...)` returns locked sections, prompts and physical targets. - `updateInstalled(...)` previews resolutions, target differences and changed ChatGPT prompts. With `apply: true`, a throwing `beforeApply` callback can show differences or cancel before files and state change. -- `installResolvedReport(...)` restores locked sections, offsets and targets. - `remove(...)` preserves custom content and deletes empty files only when their - lock records that the tool created them. -- `renderChatGPT(prompt:...)` renders locked sections plus a custom append file - without markers. Prompts live in `instructions.chatgpt`. -- `doctor(...)` checks drift, scope duplication, Claude forwarding, Codex - overrides and size limits, newer matching source revisions and uncommitted - sources. Its `projectRoots` overload audits explicit projects without writing. -- `initializeInstructions(named:directory:)` creates a valid source skeleton. - -Project recipients share `AGENTS.md` except Gemini CLI, which uses `GEMINI.md`. -Claude project files receive only a managed import when forwarding is needed. -User locations honor `CODEX_HOME`, `CLAUDE_CONFIG_DIR` and `XDG_CONFIG_HOME`; -Codex and Claude use separate files. Lost-lock update reports the comparison; -apply reconstructs the lock without claiming ownership of pre-existing files. -Codex diagnostics accept effective discovery settings from the consumer, -including trusted project configuration overrides. +- `installResolvedReport(...)` restores the locked renderings. `remove(...)` + deletes a target that no longer receives sections while it still equals its + locked rendering. +- `renderChatGPT(prompt:...)` renders locked sections plus a custom append file. + Prompts live in `instructions.chatgpt`. +- `doctor(...)` checks missing, drifted and hand-written targets, changed own + files, links, scope duplication, Claude forwarding, Codex overrides and the + project size budget, newer matching source revisions and uncommitted sources. + Its `projectRoots` overload audits explicit projects without writing. +- `export(projectRoots:...)` reads the user lock and the given projects' locks + into a mapping of targets to sections, without writing. +- `initializeInstructions(named:directory:)` creates a valid file skeleton. + +A target is a notice line followed by the sections in declared order. A section +with `paths` gets a line naming its patterns and, in project scope, is written +to the `AGENTS.md` of the directory the patterns share. Project recipients +share `AGENTS.md` except Gemini CLI, which uses `GEMINI.md`. Claude project +files receive only a managed import when forwarding is needed. User locations +honor `CODEX_HOME`, `CLAUDE_CONFIG_DIR` and `XDG_CONFIG_HOME`; Codex and Claude +use separate files. Codex diagnostics accept effective discovery settings from +the consumer, including trusted project configuration overrides. Claude forwarding recognizes standalone, unquoted and unformatted imports of that project's `AGENTS.md` outside code and HTML, including managed import @@ -243,8 +252,8 @@ contracts, target paths, read-only inspection and deletion rules. module boundaries and public workflows. - [State and cache](Documentation/Architecture/State.md): declarations, resolved state, transactions and installation invariants. -- [Instruction lifecycle](Documentation/Architecture/Instructions.md): section - selection, targets, prompts and diagnostics. +- [Instruction lifecycle](Documentation/Architecture/Instructions.md): + instructions files, generated targets, prompts and diagnostics. - [Watch API](Documentation/Architecture/Watch.md): subscriptions, comparisons and seen baselines. - [Combined updates](Documentation/Architecture/Updates.md): reports, preparation, diff --git a/Sources/AgentsCore/Declaration.swift b/Sources/AgentsCore/Declaration.swift index c8f1017..359ea00 100644 --- a/Sources/AgentsCore/Declaration.swift +++ b/Sources/AgentsCore/Declaration.swift @@ -238,15 +238,28 @@ public struct Declaration: Codable, Equatable, Sendable { + (instructions?.chatgpt ?? [:]).values.flatMap(\.sections) { let parts = reference.split(separator: ":", omittingEmptySubsequences: false) - guard parts.count == 2, sources[String(parts[0])] != nil, !parts[1].isEmpty else { - throw CoreError.invalidState("invalid section reference: \(reference)") - } + let valid = + parts.count == 1 + ? Self.isInstructionName(reference) + : parts.count == 2 && sources[String(parts[0])] != nil + && Self.isInstructionName(String(parts[1])) + guard valid else { throw CoreError.invalidState("invalid section reference: \(reference)") } } for prompt in (instructions?.chatgpt ?? [:]).values { if let append = prompt.append { _ = try PathSafety.sanitizeSubpath(append) } } } + /// Whether every `/`-separated segment of an instructions name uses lowercase letters, digits + /// and hyphens. A reference without an alias names the project's own instructions. + package static func isInstructionName(_ name: String) -> Bool { + let segments = name.split(separator: "/", omittingEmptySubsequences: false) + return !segments.isEmpty + && segments.allSatisfy { + $0.range(of: #"^[a-z0-9][a-z0-9-]*$"#, options: .regularExpression) != nil + } + } + package static func validateNames(_ names: [String]) throws { guard Set(names).count == names.count, names.allSatisfy({ $0 == PathSafety.sanitizeName($0) }) else { diff --git a/Sources/AgentsCore/InstructionLocations.swift b/Sources/AgentsCore/InstructionLocations.swift index 63c8819..63e3f91 100644 --- a/Sources/AgentsCore/InstructionLocations.swift +++ b/Sources/AgentsCore/InstructionLocations.swift @@ -6,6 +6,19 @@ package enum InstructionLocations { "AGENTS.md", "GEMINI.md", "CLAUDE.md", ".claude/CLAUDE.md", "CLAUDE.local.md", ] + /// Whether a project-relative path is a root instruction file, or a generated `AGENTS.md` or + /// `GEMINI.md` in a project directory outside `.git` and `.agent`. + package static func isProjectTarget(_ relative: String) -> Bool { + if projectPaths.contains(relative) { return true } + let parts = relative.split(separator: "/", omittingEmptySubsequences: false) + guard parts.count >= 2, let name = parts.last, ["AGENTS.md", "GEMINI.md"].contains(name) + else { return false } + let directories = parts.dropLast() + return directories.allSatisfy { + !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("\\") && !$0.contains("\0") + } && directories.first != ".git" && directories.first != ".agent" + } + package static func file( for agent: AgentID, scope: InstallScope, environment: RuntimeEnvironment ) -> URL? { @@ -53,7 +66,10 @@ package enum InstructionLocations { } let allowed: [URL] if store.scope == .project { - allowed = projectPaths.map { store.environment.projectDirectory.appendingPathComponent($0) } + guard isProjectTarget(key) else { + throw CoreError.unsafePath("unregistered instruction target: \(key)") + } + allowed = [store.environment.projectDirectory.appendingPathComponent(key)] } else { allowed = AgentID.allCases.compactMap { self.file(for: $0, scope: .user, environment: store.environment) diff --git a/Sources/AgentsCore/ResolvedState.swift b/Sources/AgentsCore/ResolvedState.swift index 9895e58..28299ef 100644 --- a/Sources/AgentsCore/ResolvedState.swift +++ b/Sources/AgentsCore/ResolvedState.swift @@ -231,11 +231,22 @@ public struct ResolvedState: Codable, Equatable, Sendable { } } for section in instructions.sections + instructions.chatgpt.values.flatMap(\.sections) { - guard let source = sources[section.source], !section.name.isEmpty else { - throw CoreError.invalidState("invalid section source or name") + guard Declaration.isInstructionName(section.name) else { + throw CoreError.invalidState("invalid section name: \(section.name)") + } + if section.source == "." { + // A project's own instructions are read live from `.agent/instructions/`; only the hash pins them. + guard section.revision == nil, section.version == nil, section.artifact == nil, + section.path.hasPrefix(".agent/instructions/") + else { throw CoreError.invalidState("own instructions take only a path and a hash") } + } else { + guard let source = sources[section.source] else { + throw CoreError.invalidState("invalid section source: \(section.source)") + } + try validatePin( + source: source, revision: section.revision, artifact: section.artifact, + path: section.path) } - try validatePin( - source: source, revision: section.revision, artifact: section.artifact, path: section.path) _ = try PathSafety.sanitizeSubpath(section.path) try StateValidation.digest(section.hash) } diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index 4785be3..f292eff 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -13,7 +13,7 @@ struct TransactionPaths { if store.scope == .project { let relative = PathSafety.relativePath( destination.path, to: base.resolvingSymlinksInPath().path) - if InstructionLocations.projectPaths.contains(relative) { + if InstructionLocations.isProjectTarget(relative) { return "instructions-project/" + relative } if destination.deletingLastPathComponent().standardizedFileURL @@ -106,7 +106,7 @@ struct TransactionPaths { throw CoreError.unsafePath("unmanaged state transaction path") } } else if key == "instructions-project", store.scope == .project { - guard InstructionLocations.projectPaths.contains(descendants.joined(separator: "/")) else { + guard InstructionLocations.isProjectTarget(descendants.joined(separator: "/")) else { throw CoreError.unsafePath("unmanaged project instruction path") } } else if key == "instructions-authoring", store.scope == .project { diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 7d6c2d8..3a1f72f 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -342,17 +342,25 @@ public struct WatchOperations: Sendable { for path in ["instructions", ".agents/instructions"] { let directory = try PathSafety.resolvedChild(base: root, subpath: path) guard FileManager.default.fileExists(atPath: directory.path) else { continue } - let handle = try DirectoryHandle(at: directory) - for file in try handle.names() where file.hasSuffix(".md") { - guard try (handle.info(file)?.st_mode ?? 0) & 0o170000 != 0o040000 else { continue } - let key = WatchItemKey(kind: .instructions, name: String(file.dropLast(3))) - guard result[key] == nil else { - throw CoreError.invalidSource("duplicate instructions name: \(key.name)") + // Instructions files are named by their path inside the container, subdirectories included. + func collect(_ handle: DirectoryHandle, prefix: String) throws { + for file in try handle.names() { + let mode = try (handle.info(file)?.st_mode ?? 0) & 0o170000 + if mode == 0o040000 { + try collect(handle.child(file), prefix: prefix + file + "/") + continue + } + guard file.hasSuffix(".md") else { continue } + let key = WatchItemKey(kind: .instructions, name: prefix + String(file.dropLast(3))) + guard result[key] == nil else { + throw CoreError.invalidSource("duplicate instructions name: \(key.name)") + } + result[key] = WatchUnit( + path: path + "/" + prefix + file, digest: nil, + files: [file: try WatchUnit.entry(file, in: handle)]) } - result[key] = WatchUnit( - path: path + "/" + file, digest: nil, - files: [file: try WatchUnit.entry(file, in: handle)]) } + try collect(DirectoryHandle(at: directory), prefix: "") } return result } diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index 048b366..fa8c4db 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -47,28 +47,56 @@ extension InstructionOperations { store.resolvedURL) } let sources = InstructionSources(store: store) + let targets = InstructionTargets(store: store) + var unchanged = true + if scope == .project { + let project = environment.projectDirectory.resolvingSymlinksInPath() + for record in lock.instructions.sections where record.source == InstructionSources.own { + let file = project.appendingPathComponent(record.path) + let current = try? Data(contentsOf: file) + if current.map(Instructions.hash) != record.hash { + unchanged = false + report( + .ownChanged, + "Own instructions file changed since the lock; run 'agents update': \(record.name)", + file) + } + } + } + let sections = + unchanged + ? try? sources.restore( + lock.instructions.sections, sources: lock.sources, cachedOnly: true + ).map(\.section) : nil for (key, target) in lock.instructions.targets.sorted(by: { $0.key < $1.key }) { do { let file = try InstructionLocations.file(for: key, store: store) - let bytes = try InstructionTargets.read(file) ?? Data() - let drift = try Instructions.detectDrift(in: bytes, lockedBlockHash: target.blockHash) - switch drift { - case .clean: break - case .missingBlock: report(.missingBlock, "Managed instruction block is missing.", file) - case .drifted: report(.drift, "Managed instruction block differs from its lock.", file) - } - if target.import == nil { - let sections = try sources.restore( - lock.instructions.sections, sources: lock.sources, cachedOnly: true) - let assembly = try Instructions.assemble( - bytes, sections: sections.map(\.section), - options: InstructionOptions( - headingOffset: target.headingOffset, replaceConflicts: true)) - for section in assembly.adoptedSections { - report(.adoption, "Custom section can be adopted: \(section)", file) + let bytes = try InstructionTargets.read(file) + if target.import != nil { + switch try Instructions.detectDrift( + in: bytes ?? Data(), lockedBlockHash: target.blockHash) + { + case .clean: break + case .missing: report(.missingTarget, "Claude import block is missing.", file) + case .drifted: report(.drift, "Claude import block differs from its lock.", file) } - for conflict in assembly.conflicts { - report(.conflict, "\(conflict.sectionID):\n\(conflict.difference)", file) + continue + } + if let bytes, !Instructions.isGenerated(bytes) { + report(.foreignTarget, "Target file was not generated by agents.", file) + } else if let bytes, Instructions.hash(bytes) != target.blockHash { + report(.drift, "Generated instructions differ from their lock.", file) + } else if bytes == nil { + report(.missingTarget, "Generated instructions file is missing.", file) + } + if let sections { + let directory = (key as NSString).deletingLastPathComponent + let group = sections.filter { scope == .user || $0.directory == directory } + if !group.isEmpty { + let text = try Instructions.render(group) + for problem in targets.linkProblems(in: text, file: file, key: key) { + report(.invalidLink, "Link '\(problem.destination)' \(problem.reason).", file) + } } } } catch { @@ -183,65 +211,83 @@ private enum InstructionDoctor { message: "Cannot read instruction discovery configuration: \(error)", path: config)) } - var directories = [user.deletingLastPathComponent()] - if scope == .project { - let cwd = environment.projectDirectory.resolvingSymlinksInPath() - let candidates = [cwd] + ancestors(of: cwd) - if let index = candidates.firstIndex(where: { - directory in + let store = StateStore(scope: scope, environment: environment) + func managed(_ file: URL) -> Bool { + lock.instructions.targets.contains { key, value in + value.agents.contains(.codex) + && (try? InstructionLocations.file(for: key, store: store)) + == InstructionLocations.physical(file) + } || (try? Data(contentsOf: file)).map(Instructions.isGenerated) == true + } + func content(_ file: URL) -> Data? { + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: file.path, isDirectory: &isDirectory), + !isDirectory.boolValue + else { return nil } + return (try? Data(contentsOf: file)) ?? Data() + } + func blank(_ data: Data) -> Bool { + String(decoding: data, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } + // The user file is loaded separately, without a size limit; only an override can hide it. + if scope == .user { + let override = user.deletingLastPathComponent().appendingPathComponent("AGENTS.override.md") + if let data = content(override), !blank(data), managed(user) { + result.append( + InstructionDiagnostic( + kind: .codexOverride, message: "AGENTS.override.md hides a managed AGENTS.md.", + path: override)) + } + return result + } + // A project chain runs from the nearest root marker down to the working directory. The first + // regular file per directory wins, even an empty one; whitespace-only files add nothing. + let project = environment.projectDirectory.resolvingSymlinksInPath() + var leaves = [project] + for key in lock.instructions.targets.keys where key.hasSuffix("/AGENTS.md") { + if let file = try? InstructionLocations.file(for: key, store: store) { + leaves.append(file.deletingLastPathComponent()) + } + } + var hidden = Set() + for leaf in leaves { + let candidates = [leaf] + ancestors(of: leaf) + let root = candidates.firstIndex { directory in configuration.rootMarkers.contains { FileManager.default.fileExists(atPath: directory.appendingPathComponent($0).path) } - }) { - directories += candidates[...index].reversed() - } else { - directories.append(cwd) } - } - var loaded: [(URL, Int)] = [] - for (index, directory) in directories.enumerated() { - let override = directory.appendingPathComponent("AGENTS.override.md") - let normal = directory.appendingPathComponent("AGENTS.md") - let overriding = (try? Data(contentsOf: override)).flatMap { $0.isEmpty ? nil : $0 } - if overriding != nil { - let managed = - lock.instructions.targets.contains { key, value in - guard value.agents.contains(.codex) else { return false } - return - (try? InstructionLocations.file( - for: key, store: StateStore(scope: scope, environment: environment))) - == InstructionLocations.physical(normal) - } - || ((try? Data(contentsOf: normal)).flatMap { - try? MarkdownDocument(bytes: $0).managedBlock() - } != nil) - if managed { + let chain = root.map { Array(candidates[...$0].reversed()) } ?? [leaf] + var loaded: [(URL, Int)] = [] + for directory in chain { + let names = ["AGENTS.override.md", "AGENTS.md"] + configuration.fallbackNames + guard + let (file, data) = names.lazy.compactMap({ name -> (URL, Data)? in + let file = directory.appendingPathComponent(name) + return content(file).map { (file, $0) } + }).first + else { continue } + if file.lastPathComponent == "AGENTS.override.md", + managed(directory.appendingPathComponent("AGENTS.md")), + hidden.insert(file.path).inserted + { result.append( InstructionDiagnostic( kind: .codexOverride, message: "AGENTS.override.md hides a managed AGENTS.md.", - path: override)) + path: file)) } + if !blank(data) { loaded.append((file, data.count)) } } - let names = - ["AGENTS.override.md", "AGENTS.md"] + (index == 0 ? [] : configuration.fallbackNames) - for name in names { - let file = directory.appendingPathComponent(name) - if let bytes = try? Data(contentsOf: file), !bytes.isEmpty { - loaded.append((file, bytes.count)) - break - } + let bytes = loaded.reduce(0) { $0 + $1.1 } + if bytes > configuration.maxBytes { + result.append( + InstructionDiagnostic( + kind: .codexSize, + message: + "Codex project instructions are \(bytes) bytes, exceeding project_doc_max_bytes (\(configuration.maxBytes)): \(loaded.map { $0.0.path }.joined(separator: ", "))", + path: leaf)) } } - let bytes = loaded.reduce(0) { $0 + $1.1 } + max(0, loaded.count - 1) * 2 - if bytes > configuration.maxBytes { - result.append( - InstructionDiagnostic( - kind: .codexSize, - message: - "Codex instruction chain is \(bytes) bytes, exceeding project_doc_max_bytes (\(configuration.maxBytes)): \(loaded.map { $0.0.path }.joined(separator: ", "))", - path: environment.projectDirectory)) - } return result } - } diff --git a/Sources/AgentsInstructions/InstructionExport.swift b/Sources/AgentsInstructions/InstructionExport.swift new file mode 100644 index 0000000..0097b29 --- /dev/null +++ b/Sources/AgentsInstructions/InstructionExport.swift @@ -0,0 +1,98 @@ +import AgentsCore +import Foundation + +/// One scope's locked instruction mapping. It describes the lock, not the files on disk. +public struct InstructionMapping: Sendable, Equatable { + public enum Status: Sendable, Equatable { + case locked + case missingLock + case pendingRecovery + case unavailable(String) + } + + public struct Target: Sendable, Equatable { + /// The lock's target key: project-relative, `~`-relative under home, or absolute. + public let target: String + public let agents: [AgentID] + /// Locked sections written to this target, in declared order; empty for a Claude import. + public let sections: [LockedSection] + /// The imported file, for a Claude forwarding target. + public let `import`: String? + } + + public let scope: InstallScope + public let root: URL + public let status: Status + public let targets: [Target] + /// Locked sections whose placement cannot be read, such as an own file changed since the lock. + public let unplaced: [LockedSection] + public let prompts: [String: [LockedSection]] +} + +extension InstructionOperations { + /// Reads the user scope and each project root's lock without fetching, recovering or writing. + /// A missing, pending or unreadable scope is reported in its status, never omitted. + public static func export( + projectRoots: [URL], environment: RuntimeEnvironment = RuntimeEnvironment() + ) -> [InstructionMapping] { + var seen = Set() + let roots = projectRoots.map(\.standardizedFileURL).filter { seen.insert($0.path).inserted } + return [mapping(scope: .user, environment: environment)] + + roots.map { root in + var runtime = environment + runtime.projectDirectory = root + return mapping(scope: .project, environment: runtime) + } + } + + private static func mapping(scope: InstallScope, environment: RuntimeEnvironment) + -> InstructionMapping + { + let store = StateStore(scope: scope, environment: environment) + let root = scope == .project ? environment.projectDirectory : environment.homeDirectory + func empty(_ status: InstructionMapping.Status) -> InstructionMapping { + InstructionMapping( + scope: scope, root: root, status: status, targets: [], unplaced: [], prompts: [:]) + } + do { + return try store.withReadLock( + onPendingRecovery: { empty(.pendingRecovery) }, + { + _ = try store.readDeclaration() + guard try store.existingData(store.resolvedURL) != nil else { + return empty(.missingLock) + } + let lock = try store.readResolved() + let sources = InstructionSources(store: store) + var directories: [String: String] = [:] + var unplaced: [LockedSection] = [] + for record in lock.instructions.sections { + if let unit = try? sources.restore([record], sources: lock.sources, cachedOnly: true) + .first + { + directories[InstructionSources.identity(record)] = + scope == .project ? unit.section.directory : "" + } else { + unplaced.append(record) + } + } + let targets = lock.instructions.targets.sorted { $0.key < $1.key }.map { key, value in + let directory = scope == .project ? (key as NSString).deletingLastPathComponent : "" + return InstructionMapping.Target( + target: key, agents: value.agents, + sections: value.import != nil + ? [] + : lock.instructions.sections.filter { + directories[InstructionSources.identity($0)] == directory + }, + import: value.import) + } + return InstructionMapping( + scope: scope, root: root, status: .locked, targets: targets, unplaced: unplaced, + prompts: lock.instructions.chatgpt.mapValues(\.sections)) + }) + } catch { + return empty(.unavailable(String(describing: error))) + } + } +} diff --git a/Sources/AgentsInstructions/InstructionFrontMatter.swift b/Sources/AgentsInstructions/InstructionFrontMatter.swift new file mode 100644 index 0000000..542cce9 --- /dev/null +++ b/Sources/AgentsInstructions/InstructionFrontMatter.swift @@ -0,0 +1,81 @@ +import Foundation + +/// The fixed front matter of an instructions file: a required `description` and optional `paths`. +/// It is a strict subset of YAML: plain, double-quoted or single-quoted scalars, and `paths` as a +/// flow list of double-quoted strings or a block list. Unknown and repeated keys are errors. +struct InstructionFrontMatter: Equatable { + let description: String + let paths: [String] + + struct Failure: Error { + let reason: String + } + + static func parse(_ lines: [String]) throws -> Self { + var description: String? + var paths: [String]? + var index = 0 + func fail(_ reason: String) -> Failure { Failure(reason: reason) } + while index < lines.count { + let line = lines[index] + index += 1 + if line.trimmingCharacters(in: .whitespaces).isEmpty || line.hasPrefix("#") { continue } + guard let colon = line.firstIndex(of: ":"), !line.hasPrefix(" "), !line.hasPrefix("\t") + else { throw fail("front matter line \(index + 1) is not a 'key: value' entry.") } + let key = String(line[.. String { + if value.hasPrefix("\"") { + guard value.count >= 2, value.hasSuffix("\""), + let decoded = try? JSONDecoder().decode(String.self, from: Data(value.utf8)) + else { throw Failure(reason: "'\(key)' has an invalid double-quoted string.") } + return decoded + } + if value.hasPrefix("'") { + let inner = value.dropFirst().dropLast() + guard value.count >= 2, value.hasSuffix("'"), + !inner.replacingOccurrences(of: "''", with: "").contains("'") + else { throw Failure(reason: "'\(key)' has an invalid single-quoted string.") } + return inner.replacingOccurrences(of: "''", with: "'") + } + let indicators = Set("[]{},&*!|>%@`#") + guard let first = value.first, !indicators.contains(first), !value.contains(": "), + !value.contains(" #") + else { throw Failure(reason: "quote the value of '\(key)'.") } + return value + } +} diff --git a/Sources/AgentsInstructions/InstructionLifecycleModels.swift b/Sources/AgentsInstructions/InstructionLifecycleModels.swift index f006aeb..3d97b97 100644 --- a/Sources/AgentsInstructions/InstructionLifecycleModels.swift +++ b/Sources/AgentsInstructions/InstructionLifecycleModels.swift @@ -35,7 +35,8 @@ public struct InstructionAddOptions: Sendable { } } -/// A validated unit discovered in the committed tree, with its immutable coordinates. +/// A validated instructions file and its coordinates: a committed source file with its pin, or a +/// project's own file with its hash. public struct InstructionUnit: Sendable, Equatable { public let record: LockedSection public let section: InstructionSection @@ -64,9 +65,11 @@ public struct InstructionTargetChange: Sendable, Equatable { public let beforeAgents: [AgentID]? /// Planned recipients in raw-value order; empty when the target is no longer managed. public let afterAgents: [AgentID] - public let assembly: InstructionAssembly - /// Nil when no previous lock entry exists. Missing files report `missingBlock`. + /// Nil when no previous lock entry exists. public let drift: InstructionDrift? + /// Whether the write replaces an existing file that agents did not generate, which needs + /// `replace`. + public let foreign: Bool /// Whether the file bytes differ; recipient-only changes do not affect this value. /// Use `InstructionUpdateReport.hasChanges` to detect any update in the report. public var changed: Bool { before != after } @@ -78,7 +81,7 @@ public struct InstructionTargetChange: Sendable, Equatable { public struct InstructionUpdateReport: Sendable, Equatable { public let sections: [InstructionSectionChange] - /// Every affected target, including unchanged adoptions after loss of a lock. + /// Every affected target, including unchanged files recorded again after loss of a lock. public let targets: [InstructionTargetChange] /// Prompts whose section bytes, order, membership or append path changed. public let changedPrompts: [String] @@ -92,12 +95,13 @@ public struct InstructionUpdateReport: Sendable, Equatable { public struct InstructionDiagnostic: Sendable, Equatable { public enum Kind: String, Sendable { - case missingBlock + case missingTarget case drift + case foreignTarget + case ownChanged + case invalidLink case invalidTarget case missingLock - case adoption - case conflict case duplicateScope case claudeForwarding case claudeAncestor diff --git a/Sources/AgentsInstructions/InstructionModels.swift b/Sources/AgentsInstructions/InstructionModels.swift index 9b3455f..187e035 100644 --- a/Sources/AgentsInstructions/InstructionModels.swift +++ b/Sources/AgentsInstructions/InstructionModels.swift @@ -3,69 +3,62 @@ import Foundation public struct InstructionSection: Sendable, Equatable { /// Caller-owned, source-qualified identity, used in reports and scope comparisons. public let id: String - /// The Markdown AST's plain text for the source heading, with whitespace trimmed and collapsed. + /// Level of the body's first heading. + public let level: Int + /// The first heading's Markdown plain text, with whitespace trimmed and collapsed. public let heading: String - /// SHA-256 of the original source bytes, including their line endings and any UTF-8 byte order mark. + public let description: String + /// Project-relative glob patterns that scope the section, in source order. + public let paths: [String] + /// SHA-256 of the original source bytes, including their line endings and any byte order mark. public let hash: String + /// The body as written into targets: no front matter, LF endings, no leading or trailing + /// blank lines, and the `paths` line after the first heading. let content: String - let document: MarkdownDocument + /// The project-relative directory whose `AGENTS.md` receives the section; empty for the root. + public var directory: String { Instructions.directory(for: paths) } } -public struct InstructionOptions: Sendable { - /// Nil recomputes from the title; install passes the locked value (zero or one). - public var headingOffset: Int? - /// Applies only to matching custom sections. Existing managed content is rendered anew. - public var replaceConflicts: Bool - - public init(headingOffset: Int? = nil, replaceConflicts: Bool = false) { - self.headingOffset = headingOffset - self.replaceConflicts = replaceConflicts - } +public enum InstructionDrift: Sendable, Equatable { + case clean + case drifted + case missing } -public struct InstructionConflict: Sendable, Equatable { - public let sectionID: String - public let existing: String - public let proposed: String - public let difference: String -} +/// A Markdown destination that needs a filesystem check, or a raw HTML link. +public struct InstructionLink: Sendable, Equatable { + public enum Kind: String, Sendable { + case link + case image + case definition + case html + } -public struct InstructionAssembly: Sendable, Equatable { - public let bytes: Data - public let headingOffset: Int - /// Includes both marker lines and a final LF; nil after removing the block. - public let block: String? - public let blockHash: String? - public let adoptedSections: [String] - public let conflicts: [InstructionConflict] - /// Difference from the previous managed block, independent of custom-section conflicts. - public let blockDifference: String? - /// The caller combines this with its locked `created` flag before deleting a file. - /// A leading UTF-8 byte order mark is file metadata and does not count as custom content. - public let hasCustomContent: Bool + public let kind: Kind + /// The destination as written; for `html`, the HTML text. + public let destination: String + /// The decoded local path without query or fragment; nil for `html`. + public let path: String? } -public enum InstructionDrift: Sendable, Equatable { - case clean - /// A hash cannot reconstruct text. Difference is nil unless the caller supplies the locked block. - case drifted(actualBlock: String, difference: String?) - case missingBlock +public struct InstructionLinkProblem: Sendable, Equatable { + public let target: String + public let destination: String + public let reason: String } public enum InstructionError: Error, Sendable, Equatable, CustomStringConvertible, LocalizedError { case invalidUTF8 case invalidSource(id: String, reason: String) - case invalidHeadingOffset(Int) - case headingOverflow(sectionID: String, level: Int, offset: Int) case duplicateHeading(heading: String, sectionIDs: [String]) - case ambiguousMatch(sectionID: String, lines: [Int]) - case conflictingSections([InstructionConflict]) case unpairedMarker(line: Int) case nestedMarker(line: Int) case multipleBlocks case invalidAssembly case invalidLockedBlock + case invalidLinks([InstructionLinkProblem]) + case unownedTargets([String]) case emptyPrompt public var description: String { @@ -73,30 +66,26 @@ public enum InstructionError: Error, Sendable, Equatable, CustomStringConvertibl case .invalidUTF8: return "Instructions must be valid UTF-8." case .invalidSource(let id, let reason): - return "Invalid instructions source '\(id)': \(reason)" - case .invalidHeadingOffset(let offset): - return "Heading offset must be 0 or 1; got \(offset)." - case .headingOverflow(let id, let level, let offset): - return - "Section '\(id)' has a level-\(level) heading that exceeds level 6 with offset \(offset)." + return "Invalid instructions file '\(id)': \(reason)" case .duplicateHeading(let heading, let ids): - return "Selected sections have the same heading '\(heading)': \(ids.joined(separator: ", "))." - case .ambiguousMatch(let id, let lines): return - "Section '\(id)' matches multiple headings at lines \(lines.map(String.init).joined(separator: ", "))." - case .conflictingSections(let conflicts): - return conflicts.map { "Conflicting section '\($0.sectionID)':\n\($0.difference)" } - .joined(separator: "\n") + "Sections in one target have the same heading '\(heading)': \(ids.joined(separator: ", "))." case .unpairedMarker(let line): return "Unpaired managed marker at line \(line)." case .nestedMarker(let line): return "Nested managed BEGIN marker at line \(line)." case .multipleBlocks: - return "The target contains more than one managed block." + return "The file contains more than one managed block." case .invalidAssembly: - return "The assembled Markdown does not contain exactly the expected managed block." + return "The assembled Markdown does not have the expected structure." case .invalidLockedBlock: - return "The supplied locked block does not match its hash or managed-block structure." + return "The locked content does not match its recorded hash." + case .invalidLinks(let problems): + return problems.map { "\($0.target): link '\($0.destination)' \($0.reason)" } + .joined(separator: "\n") + case .unownedTargets(let targets): + return + "Files that agents did not generate are in the way: \(targets.joined(separator: ", "))." case .emptyPrompt: return "A ChatGPT prompt must have at least one locked section." } diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 5ec73bf..91556e9 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -28,29 +28,38 @@ public enum InstructionOperations { var declaration = previousDeclaration let selectionChanged = CoreError.invalidState( "automatic instruction selection changed during discovery; retry the command") - let source: SourceDeclaration + let sources = InstructionSources(store: store) let id: String - do { - source = try sourceDeclaration(options, declaration: declaration) - id = try source.identity(environment: options.environment) - } catch { - if automaticSelection != nil { throw selectionChanged } - throw error - } - if let automaticSelection, automaticSelection.sourceID != id { throw selectionChanged } - let existing = try declaration.sources.keys.sorted().first { - try declaration.sources[$0]?.identity(environment: options.environment) == id - } - let alias = options.alias ?? existing ?? declaration.derivedAlias(for: source.location) - if let current = declaration.sources[alias], - try current.identity(environment: options.environment) != id - { - throw CoreError.invalidSource("source alias already refers to another source: \(alias)") + let alias: String? + let available: [InstructionUnit] + if options.source == InstructionSources.own { + id = InstructionSources.own + alias = nil + available = try sources.own() + } else { + let source: SourceDeclaration + do { + source = try sourceDeclaration(options, declaration: declaration) + id = try source.identity(environment: options.environment) + } catch { + if automaticSelection != nil { throw selectionChanged } + throw error + } + if let automaticSelection, automaticSelection.sourceID != id { throw selectionChanged } + let existing = try declaration.sources.keys.sorted().first { + try declaration.sources[$0]?.identity(environment: options.environment) == id + } + let name = options.alias ?? existing ?? declaration.derivedAlias(for: source.location) + if let current = declaration.sources[name], + try current.identity(environment: options.environment) != id + { + throw CoreError.invalidSource("source alias already refers to another source: \(name)") + } + declaration.sources[name] = source + try declaration.validate(environment: options.environment) + alias = name + available = try sources.discover(source, cacheSource: apply) } - declaration.sources[alias] = source - try declaration.validate(environment: options.environment) - let sources = InstructionSources(store: store) - let available = try sources.discover(source, cacheSource: apply) guard options.listOnly || automaticSelection != nil || !available.isEmpty else { throw CoreError.notFound("source provides no instructions") } @@ -75,7 +84,7 @@ public enum InstructionOperations { guard !selected.isEmpty else { throw CoreError.notFound("source provides no instructions") } var instructions = declaration.instructions ?? InstructionsDeclaration() if let agents = options.agents { instructions.agents = agents } - let references = selected.map { alias + ":" + $0.record.name } + let references = selected.map { (alias.map { $0 + ":" } ?? "") + $0.record.name } for reference in references where !instructions.sections.contains(reference) { instructions.sections.append(reference) } @@ -84,9 +93,9 @@ public enum InstructionOperations { declaration: declaration, previous: previous, sources: sources, resolving: Set(references)) let plan = try plan( declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, prepared: prepared, store: store, - replace: options.replace) + previous: previous, prepared: prepared, store: store) try plan.lock.validate() + if !options.replace { try requireOwnership(plan.report) } try beforeApply?(plan.report) try Self.apply( declaration: declaration, next: plan.lock, report: plan.report, sources: sources) @@ -105,6 +114,14 @@ public enum InstructionOperations { } } + /// The project's own instructions in `.agent/instructions/`, read from the working tree. + public static func listOwn(environment: RuntimeEnvironment = RuntimeEnvironment()) throws + -> [InstructionUnit] + { + let store = StateStore(scope: .project, environment: environment) + return try operate(store, apply: false) { _, _ in try InstructionSources(store: store).own() } + } + /// Includes missing targets; doctor supplies their disk status. public static func listManaged( scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() @@ -115,10 +132,12 @@ public enum InstructionOperations { } /// Resolves declared content and reports every affected target before any replacement. - /// `agents` replaces the scope's instruction recipients when applying. + /// `agents` replaces the scope's instruction recipients when applying. Applying over a file that + /// agents did not generate requires `replace`. public static func updateInstalled( scope: InstallScope = .project, agents: [AgentID]? = nil, environment: RuntimeEnvironment = RuntimeEnvironment(), apply: Bool = false, + replace: Bool = false, beforeApply: ((InstructionUpdateReport) throws -> Void)? = nil ) throws -> InstructionUpdateReport { let store = StateStore(scope: scope, environment: environment) @@ -133,9 +152,10 @@ public enum InstructionOperations { let resolutions = try SourceResolutionSession(store: store) let plan = try prepareUpdate( store: store, declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, resolutions: resolutions) + previous: previous, resolutions: resolutions, replace: replace) try plan.next.validate() if apply { + if !replace { try requireOwnership(plan.report) } try beforeApply?(plan.report) try baseline.validate() try plan.validate() @@ -156,19 +176,21 @@ public enum InstructionOperations { } /// Prepares instruction-owned records; the caller validates the complete generation after assembly. + /// Validation fails when the plan writes over a file agents did not generate without `replace`. package static func prepareUpdate( store: StateStore, declaration: Declaration, previousDeclaration: Declaration, - previous: ResolvedState, resolutions: SourceResolutionSession + previous: ResolvedState, resolutions: SourceResolutionSession, replace: Bool = false ) throws -> InstructionUpdatePlan { let sources = InstructionSources(store: store, resolutions: resolutions) let prepared = try prepare(declaration: declaration, previous: previous, sources: sources) let plan = try plan( declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, prepared: prepared, store: store, replace: true) - return try InstructionUpdatePlan(next: plan.lock, report: plan.report, sources: sources) + previous: previous, prepared: prepared, store: store) + return try InstructionUpdatePlan( + next: plan.lock, report: plan.report, sources: sources, replace: replace) } - /// Restores only recorded pins, targets and heading offsets, without changing either state file. + /// Restores only recorded pins and targets, without changing either state file. public static func installResolvedReport( scope: InstallScope = .project, environment: RuntimeEnvironment = RuntimeEnvironment() ) throws -> InstructionUpdateReport { @@ -181,7 +203,7 @@ public enum InstructionOperations { sections: sources.restore(prompt.sections, sources: lock.sources).map(\.section)) } let targets = try InstructionTargets(store: store).plan( - sections: sections.map(\.section), agents: [], previous: lock.instructions, replace: false, + sections: sections.map(\.section), agents: [], previous: lock.instructions, restoring: true) let report = InstructionUpdateReport( sections: [], targets: targets.changes, changedPrompts: [], @@ -230,9 +252,9 @@ public enum InstructionOperations { declaration: declaration, previous: previous, sources: sources, resolving: []) let plan = try plan( declaration: declaration, previousDeclaration: previousDeclaration, - previous: previous, prepared: prepared, store: store, - replace: false) + previous: previous, prepared: prepared, store: store) try plan.lock.validate() + try requireOwnership(plan.report) try beforeApply?(plan.report) try apply(declaration: declaration, next: plan.lock, report: plan.report, sources: sources) return plan.report @@ -263,11 +285,13 @@ public enum InstructionOperations { } } - /// Creates `.md` in the supplied directory without replacing an existing entry. + /// Creates `.md` with the required front matter in the supplied directory, without + /// replacing an existing entry. @discardableResult public static func initializeInstructions(named name: String, directory: URL) throws -> URL { - guard name == PathSafety.sanitizeName(name) else { - throw CoreError.invalidSource("instruction name must be a filesystem identity") + guard Declaration.isInstructionName(name), !name.contains("/") else { + throw CoreError.invalidSource( + "instruction names use lowercase letters, digits and hyphens: \(name)") } let environment = RuntimeEnvironment( projectDirectory: directory, homeDirectory: directory, environment: [:]) @@ -277,7 +301,9 @@ public enum InstructionOperations { guard try InstructionTargets.read(file) == nil else { throw CoreError.invalidSource("instruction file already exists: \(file.path)") } - let bytes = Data("# \(name)\n\nWrite the instructions here.\n".utf8) + let bytes = Data( + "---\ndescription: Describe what these instructions make the agent do.\n---\n# \(name)\n\nWrite the instructions here.\n" + .utf8) _ = try Instructions.validateSource(bytes, id: name) let transaction = FileTransaction(store: store) try transaction.replace(file, content: nil, data: bytes) @@ -297,12 +323,14 @@ public enum InstructionOperations { previous.instructions.sections + previous.instructions.chatgpt.values.flatMap(\.sections) func units(_ references: [String], locked: [LockedSection]) throws -> [InstructionUnit] { try references.map { reference in - let parts = reference.split(separator: ":").map(String.init) - let id = try declaration.sources[parts[0]]!.identity(environment: sources.store.environment) - if let resolving, !resolving.contains(reference), - let record = (locked + old).first(where: { $0.source == id && $0.name == parts[1] }) + // Own instructions are never pinned, so they always resolve from the working tree. + if let (alias, name) = InstructionSources.split(reference), let resolving, + !resolving.contains(reference) { - return try sources.restore([record], sources: previous.sources)[0] + let id = try declaration.sources[alias]!.identity(environment: sources.store.environment) + if let record = (locked + old).first(where: { $0.source == id && $0.name == name }) { + return try sources.restore([record], sources: previous.sources)[0] + } } return try sources.resolve(references: [reference], declaration: declaration, lock: &next)[ 0] @@ -324,17 +352,13 @@ public enum InstructionOperations { private static func plan( declaration: Declaration, previousDeclaration: Declaration, previous: ResolvedState, - prepared: (lock: ResolvedState, sections: [InstructionSection]), store: StateStore, - replace: Bool + prepared: (lock: ResolvedState, sections: [InstructionSection]), store: StateStore ) throws -> (lock: ResolvedState, report: InstructionUpdateReport) { var next = prepared.lock - if !prepared.sections.isEmpty { - _ = try Instructions.renderChatGPT(sections: prepared.sections) - } let targets = try InstructionTargets(store: store).plan( sections: prepared.sections, agents: declaration.instructions?.agents ?? declaration.defaultAgents, - previous: previous.instructions, replace: replace) + previous: previous.instructions) next.instructions.targets = targets.targets try InstructionTargets.validateSourceDirectories(targets.changes, sources: next.sources) let before = previous.instructions.sections @@ -366,6 +390,12 @@ public enum InstructionOperations { ) } + /// Stops a write over files that agents did not generate, naming them. + static func requireOwnership(_ report: InstructionUpdateReport) throws { + let foreign = report.targets.filter(\.foreign).map(\.target) + guard foreign.isEmpty else { throw InstructionError.unownedTargets(foreign) } + } + private static func apply( declaration: Declaration, next: ResolvedState, report: InstructionUpdateReport, sources: InstructionSources, writeState: Bool = true diff --git a/Sources/AgentsInstructions/InstructionSources.swift b/Sources/AgentsInstructions/InstructionSources.swift index 1df96ee..bcd600c 100644 --- a/Sources/AgentsInstructions/InstructionSources.swift +++ b/Sources/AgentsInstructions/InstructionSources.swift @@ -2,11 +2,18 @@ import AgentsCore import Foundation final class InstructionSources { + /// The lock's source for a project's own instructions, which are read live and never pinned. + static let own = "." + /// The project's own instructions container, relative to the project root. + static let ownContainer = ".agent/instructions" + static let containers = ["instructions", ".agents/instructions"] + let store: StateStore let cache: SourceCache let resolutions: SourceResolutionSession? private var discovered: [String: [InstructionUnit]] = [:] private var restored: [String: InstructionSection] = [:] + private var ownUnits: [InstructionUnit]? init(store: StateStore, resolutions: SourceResolutionSession? = nil) { self.resolutions = resolutions @@ -39,23 +46,9 @@ final class InstructionSources { func read(_ pin: SourceRevision, _ tree: URL) throws -> [InstructionUnit] { let root = try PathSafety.resolvedChild(base: tree, subpath: source.path ?? ".") var units: [InstructionUnit] = [] - var names = Set() - for container in ["instructions", ".agents/instructions"] { + for container in Self.containers { let directory = root.appendingPathComponent(container) - guard FileManager.default.fileExists(atPath: directory.path) else { continue } - try Self.contained(directory, in: tree) - for file in try FileManager.default.contentsOfDirectory( - at: directory, includingPropertiesForKeys: [.isRegularFileKey] - ).sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) - where file.pathExtension == "md" { - try Self.contained(file, in: tree) - guard try file.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile == true else { - continue - } - let name = file.deletingPathExtension().lastPathComponent - guard !name.isEmpty, !name.contains(":"), names.insert(name).inserted else { - throw CoreError.invalidSource("duplicate or invalid instruction name: \(name)") - } + for (name, file) in try Self.files(in: directory, tree: tree) { let section = try Instructions.validateSource(Data(contentsOf: file), id: id + ":" + name) units.append( InstructionUnit( @@ -65,7 +58,7 @@ final class InstructionSources { section: section)) } } - return units.sorted { $0.record.name < $1.record.name } + return try Self.unique(units) } let units = try resolutions.map { try $0.withSnapshot(source, read) } @@ -74,16 +67,41 @@ final class InstructionSources { return units } + /// The project's own instructions, read from the working tree as it is. + func own() throws -> [InstructionUnit] { + if let ownUnits { return ownUnits } + guard store.scope == .project else { + throw CoreError.invalidState("own instructions exist only in project scope") + } + let project = store.environment.projectDirectory.resolvingSymlinksInPath() + let directory = project.appendingPathComponent(Self.ownContainer) + let units = try Self.unique( + Self.files(in: directory, tree: project).map { name, file in + let section = try Instructions.validateSource(Data(contentsOf: file), id: name) + return InstructionUnit( + record: LockedSection( + name: name, source: Self.own, + path: PathSafety.relativePath(file.path, to: project.path), hash: section.hash), + section: section) + }) + ownUnits = units + return units + } + func resolve( references: [String], declaration: Declaration, lock: inout ResolvedState ) throws -> [InstructionUnit] { try references.map { reference in - let parts = reference.split(separator: ":", omittingEmptySubsequences: false).map(String.init) - guard parts.count == 2, let source = declaration.sources[parts[0]] else { + guard let (alias, name) = Self.split(reference) else { + guard let unit = try own().first(where: { $0.record.name == reference }) else { + throw CoreError.notFound("own instructions file: \(reference)") + } + return unit + } + guard let source = declaration.sources[alias] else { throw CoreError.invalidState("invalid instruction reference: \(reference)") } - let units = try discover(source) - guard let unit = units.first(where: { $0.record.name == parts[1] }) else { + guard let unit = try discover(source).first(where: { $0.record.name == name }) else { throw CoreError.notFound("instruction section: \(reference)") } lock.sources[unit.record.source] = lockedSource(source) @@ -97,6 +115,15 @@ final class InstructionSources { -> [InstructionUnit] { try records.map { record in + if record.source == Self.own { + guard let unit = try own().first(where: { $0.record.path == record.path }), + unit.record.hash == record.hash + else { + throw CoreError.invalidState( + "own instructions file changed since the lock: \(record.name); run 'agents update'") + } + return unit + } guard let source = sources[record.source], let revision = record.revision, source.kind != .wellKnown else { throw CoreError.invalidState("instruction section requires a locked Git revision") } @@ -132,7 +159,7 @@ final class InstructionSources { func retain(_ lock: ResolvedState) throws { let records = lock.instructions.sections + lock.instructions.chatgpt.values.flatMap(\.sections) - for record in records { + for record in records where record.source != Self.own { guard let source = lock.sources[record.source], let revision = record.revision else { throw CoreError.invalidState("missing instruction pin") } @@ -145,6 +172,12 @@ final class InstructionSources { } } + /// `alias:name` for a declared source, or nil for a bare name of the project's own instructions. + static func split(_ reference: String) -> (alias: String, name: String)? { + guard let colon = reference.firstIndex(of: ":") else { return nil } + return (String(reference[.. String { record.source + ":" + record.name } static func contained(_ file: URL, in root: URL) throws { @@ -153,4 +186,44 @@ final class InstructionSources { throw CoreError.unsafePath("instruction path escapes its root") } } + + /// The `.md` files below a container, by name. Symbolic links and invalid names are errors. + private static func files(in directory: URL, tree: URL) throws -> [(String, URL)] { + guard FileManager.default.fileExists(atPath: directory.path) else { return [] } + try contained(directory, in: tree) + var result: [(String, URL)] = [] + func walk(_ directory: URL, prefix: String) throws { + let keys: [URLResourceKey] = [.isSymbolicLinkKey, .isDirectoryKey, .isRegularFileKey] + for entry in try FileManager.default.contentsOfDirectory( + at: directory, includingPropertiesForKeys: keys + ).sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) { + let values = try entry.resourceValues(forKeys: Set(keys)) + let component = entry.lastPathComponent + if values.isSymbolicLink == true { + throw CoreError.invalidSource( + "instructions containers hold no symbolic links: \(prefix + component)") + } + if values.isDirectory == true { + try walk(entry, prefix: prefix + component + "/") + } else if values.isRegularFile == true, entry.pathExtension == "md" { + let name = prefix + entry.deletingPathExtension().lastPathComponent + guard Declaration.isInstructionName(name) else { + throw CoreError.invalidSource( + "instruction names use lowercase letters, digits and hyphens: \(name)") + } + result.append((name, entry)) + } + } + } + try walk(directory, prefix: "") + return result + } + + private static func unique(_ units: [InstructionUnit]) throws -> [InstructionUnit] { + var names = Set() + for unit in units where !names.insert(unit.record.name).inserted { + throw CoreError.invalidSource("duplicate instruction name: \(unit.record.name)") + } + return units.sorted { $0.record.name < $1.record.name } + } } diff --git a/Sources/AgentsInstructions/InstructionTargets.swift b/Sources/AgentsInstructions/InstructionTargets.swift index 32697de..bb0d33e 100644 --- a/Sources/AgentsInstructions/InstructionTargets.swift +++ b/Sources/AgentsInstructions/InstructionTargets.swift @@ -4,99 +4,196 @@ import Foundation struct InstructionTargets { let store: StateStore + /// Plans every generated target from `sections` in declared order, the Claude import, and the + /// removal of targets that no longer receive sections. `restoring` keeps the locked recipients + /// and requires each rendering to match its locked hash. func plan( sections: [InstructionSection], agents: [AgentID], previous: LockedInstructions, - replace: Bool, restoring: Bool = false + restoring: Bool = false ) throws -> (targets: [String: LockedTarget], changes: [InstructionTargetChange]) { var targets: [String: LockedTarget] = [:] - if restoring { - targets = previous.targets - } else if !sections.isEmpty { - for agent in Set(agents) { - guard - let logical = InstructionLocations.file( - for: agent, scope: store.scope, environment: store.environment) - else { continue } - let file = logical.resolvingSymlinksInPath() - let key = InstructionLocations.key(for: file, store: store) - _ = try InstructionLocations.file(for: key, store: store) - if targets[key] != nil { - targets[key]?.agents.append(agent) - } else { - targets[key] = LockedTarget( - agents: [agent], headingOffset: 0, blockHash: "", created: false) - } + var rendered: [String: String] = [:] + if !sections.isEmpty { + let recipients = + restoring + ? Array(Set(previous.targets.values.filter { $0.import == nil }.flatMap(\.agents))) + : Array(Set(agents)) + var groups: [String: [InstructionSection]] = [:] + var order: [String] = [] + for section in sections { + let directory = store.scope == .project ? section.directory : "" + if groups[directory] == nil { order.append(directory) } + groups[directory, default: []].append(section) } - if store.scope == .project, agents.contains(.claudeCode) { - let files = try claudeFiles() - let forwarding = try ClaudeForwarding.classify(files) - let path: ClaudeInstructionPath? - switch forwarding { - case .automatic: path = nil - case .needsImport(let candidate): path = candidate - case .forwarding(let candidate): - let file = files.first { $0.path == candidate } - let managed = - try file.map { try MarkdownDocument(bytes: $0.bytes).managedBlock() != nil } ?? false - path = file?.isSymbolicLinkToAgents == true || !managed ? nil : candidate - } - if let path { - let file = store.environment.projectDirectory.appendingPathComponent(path.rawValue) - let key = InstructionLocations.key(for: InstructionLocations.physical(file), store: store) - guard targets[key] == nil else { - throw CoreError.invalidState("forwarding overlaps a section target") + for directory in order { + let text = try Instructions.render(groups[directory]!) + for agent in recipients.sorted(by: { $0.rawValue < $1.rawValue }) { + guard let file = try location(for: agent, directory: directory) else { continue } + let key = InstructionLocations.key(for: file, store: store) + _ = try InstructionLocations.file(for: key, store: store) + if targets[key] != nil { + targets[key]?.agents.append(agent) + } else { + rendered[key] = text + targets[key] = LockedTarget( + agents: [agent], headingOffset: 0, blockHash: Instructions.hash(Data(text.utf8)), + created: false) } - targets[key] = LockedTarget( - agents: [.claudeCode], import: String(path.importLine.dropFirst()), blockHash: "", - created: false) } } + if store.scope == .project, recipients.contains(.claudeCode), targets["AGENTS.md"] != nil, + let path = try forwardingPath() + { + let file = store.environment.projectDirectory.appendingPathComponent(path.rawValue) + let key = InstructionLocations.key(for: InstructionLocations.physical(file), store: store) + guard targets[key] == nil else { + throw CoreError.invalidState("forwarding overlaps an instruction target") + } + targets[key] = LockedTarget( + agents: [.claudeCode], import: String(path.importLine.dropFirst()), blockHash: "", + created: false) + } } var changes: [InstructionTargetChange] = [] + var problems: [InstructionLinkProblem] = [] for key in Set(previous.targets.keys).union(targets.keys).sorted() { let file = try InstructionLocations.file(for: key, store: store) let before = try Self.read(file) let old = previous.targets[key] - let drift = try old.map { - try Instructions.detectDrift(in: before ?? Data(), lockedBlockHash: $0.blockHash) + var after: Data? + var foreign = false + if let target = targets[key], let reference = target.import { + guard store.scope == .project, let path = ClaudeInstructionPath(rawValue: key), + reference == String(path.importLine.dropFirst()) + else { throw CoreError.invalidState("invalid Claude forwarding target") } + let edit = try Self.importBlock(in: before ?? Data(), at: path) + after = edit.bytes + targets[key]?.blockHash = edit.blockHash + targets[key]?.created = old?.created ?? (before == nil) + } else if let text = rendered[key] { + guard store.scope == .user || directoryExists(of: file) else { + throw CoreError.notFound("the directory of instruction target \(key)") + } + after = Data(text.utf8) + foreign = + before != nil && before != after && old == nil && !Instructions.isGenerated(before!) + if restoring, targets[key]?.blockHash != old?.blockHash { + throw InstructionError.invalidLockedBlock + } + problems += linkProblems(in: text, file: file, key: key) + } else if let old, old.import != nil { + let edit = try Instructions.removeBlock(from: before ?? Data()) + let delete = old.created && !edit.hasCustomContent + after = delete || before == nil ? nil : edit.bytes + } else if let old, let before { + // A target that no longer receives sections is deleted only while it is the locked + // rendering; a drifted file is kept for its owner to resolve. + after = Instructions.hash(before) == old.blockHash ? nil : before } - let assembly: InstructionAssembly - if let target = targets[key] { - if let reference = target.import { - guard store.scope == .project, - let path = ClaudeInstructionPath(rawValue: key), - reference == String(path.importLine.dropFirst()) - else { throw CoreError.invalidState("invalid Claude forwarding target") } - assembly = try Self.importBlock(in: before ?? Data(), at: path) - } else { - guard !sections.isEmpty else { - throw CoreError.invalidState("instruction target has no locked sections") - } - assembly = try Instructions.assemble( - before ?? Data(), sections: sections, - options: InstructionOptions( - headingOffset: restoring ? target.headingOffset : nil, replaceConflicts: replace)) + let drift = try old.map { old -> InstructionDrift in + guard let before else { return .missing } + if old.import != nil { + return try Instructions.detectDrift(in: before, lockedBlockHash: old.blockHash) } - guard let blockHash = assembly.blockHash else { throw InstructionError.invalidAssembly } - if restoring, blockHash != target.blockHash { throw InstructionError.invalidLockedBlock } - targets[key]?.blockHash = blockHash - targets[key]?.headingOffset = target.import == nil ? assembly.headingOffset : nil - targets[key]?.created = old?.created ?? (before == nil) - targets[key]?.agents.sort { $0.rawValue < $1.rawValue } - } else { - assembly = try Instructions.remove(from: before ?? Data()) + return Instructions.hash(before) == old.blockHash ? .clean : .drifted } - let delete = targets[key] == nil && old?.created == true && !assembly.hasCustomContent - let after = delete || (before == nil && targets[key] == nil) ? nil : assembly.bytes + targets[key]?.agents.sort { $0.rawValue < $1.rawValue } changes.append( InstructionTargetChange( target: key, url: file, before: before, after: after, beforeAgents: old?.agents.sorted { $0.rawValue < $1.rawValue }, - afterAgents: targets[key]?.agents ?? [], assembly: assembly, drift: drift)) + afterAgents: targets[key]?.agents ?? [], drift: drift, foreign: foreign)) } + guard problems.isEmpty else { throw InstructionError.invalidLinks(problems) } return (targets, changes) } + /// The file an agent reads for sections placed in `directory`, or nil when the agent has no file. + private func location(for agent: AgentID, directory: String) throws -> URL? { + guard + let root = InstructionLocations.file( + for: agent, scope: store.scope, environment: store.environment) + else { return nil } + let file = + store.scope == .project && !directory.isEmpty + ? store.environment.projectDirectory.appendingPathComponent(directory) + .appendingPathComponent(root.lastPathComponent) + : root + return InstructionLocations.physical(file) + } + + private func directoryExists(of file: URL) -> Bool { + var isDirectory: ObjCBool = false + return FileManager.default.fileExists( + atPath: file.deletingLastPathComponent().path, isDirectory: &isDirectory) + && isDirectory.boolValue + } + + /// The Claude file that needs a managed import of `AGENTS.md`, or nil when Claude Code already + /// reads it: no project Claude file, a symbolic link to `AGENTS.md`, or a standalone import. + private func forwardingPath() throws -> ClaudeInstructionPath? { + let files = try claudeFiles() + switch try ClaudeForwarding.classify(files) { + case .automatic: return nil + case .needsImport(let candidate): return candidate + case .forwarding(let candidate): + let file = files.first { $0.path == candidate } + let managed = + try file.map { try MarkdownDocument(bytes: $0.bytes).managedBlock() != nil } ?? false + return file?.isSymbolicLinkToAgents == true || !managed ? nil : candidate + } + } + + /// Links in a rendered target that do not resolve, from the target file, to a regular file in + /// the checkout being written. User targets belong to no checkout, so every local link fails. + func linkProblems(in text: String, file: URL, key: String) -> [InstructionLinkProblem] { + var problems: [InstructionLinkProblem] = [] + let root = store.environment.projectDirectory.resolvingSymlinksInPath() + for link in Instructions.localLinks(in: text) { + func problem(_ reason: String) { + problems.append( + InstructionLinkProblem(target: key, destination: link.destination, reason: reason)) + } + guard link.kind != .html else { + problem("is a raw HTML link; use a Markdown link") + continue + } + guard let path = link.path, !path.isEmpty else { + problem("has an empty destination") + continue + } + guard store.scope == .project else { + problem("points to a local file; user instructions cannot link to local files") + continue + } + let resolved = + (path.hasPrefix("/") + ? URL(fileURLWithPath: path) + : file.deletingLastPathComponent().appendingPathComponent(path)) + .standardizedFileURL.resolvingSymlinksInPath() + guard PathSafety.isContained(resolved, in: root), resolved != root else { + problem("points outside the checkout being written") + continue + } + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: resolved.path, isDirectory: &isDirectory), + !isDirectory.boolValue + else { + problem("does not resolve to an existing file") + continue + } + var cursor = resolved.deletingLastPathComponent() + while cursor.path.count > root.path.count { + if FileManager.default.fileExists(atPath: cursor.appendingPathComponent(".git").path) { + problem("points into another repository or worktree") + break + } + cursor.deleteLastPathComponent() + } + } + return problems + } + func claudeFiles() throws -> [ClaudeInstructionFile] { let agents = store.environment.projectDirectory.appendingPathComponent("AGENTS.md") .resolvingSymlinksInPath() @@ -114,18 +211,22 @@ struct InstructionTargets { } } + /// Rejects targets inside an instructions container of a local source. static func validateSourceDirectories( _ changes: [InstructionTargetChange], sources: [String: LockedSource] ) throws { for source in sources where source.value.kind == .local { let root = URL(fileURLWithPath: String(source.key.dropFirst("local:".count))) let search = try PathSafety.resolvedChild(base: root, subpath: source.value.path ?? ".") - for container in ["instructions", ".agents/instructions"] { + for container in InstructionSources.containers { let directory = search.appendingPathComponent(container).resolvingSymlinksInPath() - guard !changes.contains(where: { $0.url.deletingLastPathComponent() == directory }) + guard + !changes.contains(where: { + PathSafety.isContained($0.url.resolvingSymlinksInPath(), in: directory) + }) else { throw CoreError.unsafePath( - "a source instructions directory cannot be an instruction target") + "a source instructions container cannot hold an instruction target") } } } @@ -143,7 +244,7 @@ struct InstructionTargets { } private static func importBlock(in bytes: Data, at path: ClaudeInstructionPath) throws - -> InstructionAssembly + -> (bytes: Data, blockHash: String) { let document = try MarkdownDocument(bytes: bytes) let old = try document.managedBlock() @@ -156,14 +257,6 @@ struct InstructionTargets { let block = ClaudeForwarding.renderBlock(for: path) let output = Instructions.separatedPrefix(before) + block + (after.isEmpty ? "" : "\n" + after) try Instructions.validateAssembly(output, expected: block) - let previous = old.map { document.normalized($0) } - return InstructionAssembly( - bytes: document.byteOrderMark + Data(output.utf8), headingOffset: 0, - block: block, blockHash: Instructions.hash(Data(block.utf8)), adoptedSections: [], - conflicts: [], - blockDifference: previous.flatMap { - $0 == block ? nil : Instructions.difference(from: $0, to: block) - }, - hasCustomContent: !before.isEmpty || !after.isEmpty) + return (document.byteOrderMark + Data(output.utf8), Instructions.hash(Data(block.utf8))) } } diff --git a/Sources/AgentsInstructions/InstructionUpdatePlan.swift b/Sources/AgentsInstructions/InstructionUpdatePlan.swift index c975ac3..327e62b 100644 --- a/Sources/AgentsInstructions/InstructionUpdatePlan.swift +++ b/Sources/AgentsInstructions/InstructionUpdatePlan.swift @@ -8,11 +8,16 @@ package final class InstructionUpdatePlan { private let sources: InstructionSources private let identities: [PathIdentity] private let forwardingInputs: [(URL, Data?)] + private let replace: Bool - init(next: ResolvedState, report: InstructionUpdateReport, sources: InstructionSources) throws { + init( + next: ResolvedState, report: InstructionUpdateReport, sources: InstructionSources, + replace: Bool + ) throws { self.next = next self.report = report self.sources = sources + self.replace = replace let store = sources.store var paths = report.targets.map(\.url) for agent in Set(report.targets.flatMap { ($0.beforeAgents ?? []) + $0.afterAgents }) { @@ -41,6 +46,7 @@ package final class InstructionUpdatePlan { } package func validate() throws { + if !replace { try InstructionOperations.requireOwnership(report) } for identity in identities { try identity.validate() } for (url, bytes) in forwardingInputs { guard try InstructionTargets.read(url) == bytes else { diff --git a/Sources/AgentsInstructions/Instructions.swift b/Sources/AgentsInstructions/Instructions.swift index 609d5b6..1d86d9b 100644 --- a/Sources/AgentsInstructions/Instructions.swift +++ b/Sources/AgentsInstructions/Instructions.swift @@ -1,174 +1,109 @@ import AgentsCore import Foundation +import Markdown /// Pure UTF-8 transformations. Filesystem access and lifecycle authorization belong to the caller. public enum Instructions { + /// The first line of every generated target. A file that starts with it is owned by the tool. + public static let notice = + "" + + /// Validates an instructions file: front matter, a body that starts with an ATX heading whose + /// level every other heading exceeds, and an end outside code and HTML blocks. public static func validateSource(_ bytes: Data, id: String) throws -> InstructionSection { - let document = try MarkdownDocument(bytes: bytes) - func invalid(_ reason: String) -> InstructionError { - .invalidSource(id: id, reason: reason) + guard String(data: bytes, encoding: .utf8) != nil else { throw InstructionError.invalidUTF8 } + func invalid(_ reason: String) -> InstructionError { .invalidSource(id: id, reason: reason) } + var text = String(decoding: bytes, as: UTF8.self) + if text.first == "\u{FEFF}" { text.removeFirst() } + let lines = MarkdownLine.parse(text).map(\.text) + guard lines.first == "---", let close = lines.dropFirst().firstIndex(of: "---") else { + throw invalid("the file must start with front matter between '---' lines.") } - guard let first = document.topLevelHeadings.first, first.level == 1, first.isATX, - document.lines[.. first.level }) + else { throw invalid("every heading after the first must be deeper than the first.") } + guard !document.endsInCode else { throw invalid("the body ends inside a code block.") } + guard !document.endsInHTML else { throw invalid("the body ends inside an HTML block.") } + if !front.paths.isEmpty { + var rest = Array(body.dropFirst()) + while rest.first.map(isBlank) == true { rest.removeFirst() } + let scope = + "Applies when working on files matching " + + front.paths.map { "`\($0)`" }.joined(separator: ", ") + "." + body = [body[0], "", scope] + (rest.isEmpty ? [] : [""] + rest) + } return InstructionSection( - id: id, heading: first.key, hash: hash(bytes), content: content, - document: MarkdownDocument(content)) + id: id, level: first.level, heading: first.key, description: front.description, + paths: front.paths, hash: hash(bytes), content: body.joined(separator: "\n")) } - /// Reports custom-section adoptions and conflicts without side effects. Empty sections remove the block. - /// A caller previewing conflicts uses `replaceConflicts`, then decides whether to persist the result. - public static func assemble( - _ bytes: Data, sections: [InstructionSection], - options: InstructionOptions = InstructionOptions() - ) throws -> InstructionAssembly { - try validateSelection(sections) - if sections.isEmpty { return try remove(from: bytes) } - let document = try MarkdownDocument(bytes: bytes) - let oldBlock = try document.managedBlock() - let selectedHeadings = Set(sections.map(\.heading)) - let title = document.topLevelHeadings.first { - $0.level == 1 && $0.lines.lowerBound < (oldBlock?.lowerBound ?? document.lines.count) - && !selectedHeadings.contains($0.key) - } - let offset = options.headingOffset ?? (title == nil ? 0 : 1) - guard (0...1).contains(offset) else { throw InstructionError.invalidHeadingOffset(offset) } - let rendered = try sections.map { try render($0, offset: offset) } - var removals: [Range] = [] - var adopted: [String] = [] - var conflicts: [InstructionConflict] = [] - for (section, content) in zip(sections, rendered) { - let identity = HeadingIdentity(level: 1 + offset, text: section.heading) - let matches = (document.sections[identity] ?? []).filter { - !(oldBlock?.contains($0.headingLine) ?? false) - } - if matches.count > 1 { - throw InstructionError.ambiguousMatch( - sectionID: section.id, lines: matches.map { $0.headingLine + 1 }) - } - if let match = matches.first { - let existing = MarkdownDocument.content( - match.contentRanges.flatMap { document.lines[$0] }[...]) - removals.append(contentsOf: match.contentRanges) - if existing.utf8.elementsEqual(content.utf8) { - adopted.append(section.id) - } else { - conflicts.append( - InstructionConflict( - sectionID: section.id, existing: existing, proposed: content, - difference: difference(from: existing, to: content))) - } - } + /// The longest directory shared by the literal prefixes of `paths`, relative to the project + /// root; empty when there are no patterns or a pattern starts with a wildcard. A pattern without + /// wildcards names a file, so its prefix is that file's directory. + public static func directory(for paths: [String]) -> String { + let prefixes = paths.map { pattern -> [Substring] in + let segments = pattern.split(separator: "/") + let literal = segments.prefix { !$0.contains("*") && !$0.contains("?") } + return literal.count == segments.count ? Array(literal.dropLast()) : Array(literal) } - if !conflicts.isEmpty && !options.replaceConflicts { - throw InstructionError.conflictingSections(conflicts) + guard var common = prefixes.first else { return "" } + for prefix in prefixes.dropFirst() { + common = zip(common, prefix).prefix { $0 == $1 }.map(\.0) } - let insertion: Int - if let oldBlock { - insertion = oldBlock.lowerBound - removals.append(oldBlock) - } else if let earliest = removals.map(\.lowerBound).min() { - insertion = earliest - } else if let title { - insertion = - document.topLevelHeadings.first { $0.lines.lowerBound >= title.lines.upperBound }? - .lines.lowerBound ?? document.lines.count - } else { - insertion = 0 - } - var prefix: [MarkdownLine] = [] - var suffix: [MarkdownLine] = [] - removals.sort { $0.lowerBound < $1.lowerBound } - var removalIndex = 0 - for (index, line) in document.lines.enumerated() { - while removalIndex < removals.count, removals[removalIndex].upperBound <= index { - removalIndex += 1 - } - if removalIndex < removals.count, removals[removalIndex].contains(index) { continue } - if index < insertion { prefix.append(line) } else { suffix.append(line) } - } - // Exactly one adjacent blank belongs to the block; any additional blanks remain custom bytes. - if prefix.last?.isBlank == true { prefix.removeLast() } - if suffix.first?.isBlank == true { suffix.removeFirst() } - let before = prefix.map(\.raw).joined() - let after = suffix.map(\.raw).joined() - let block = - MarkdownDocument.begin + "\n" + rendered.joined(separator: "\n\n") - + "\n" + MarkdownDocument.end + "\n" - let output = separatedPrefix(before) + block + (after.isEmpty ? "" : "\n" + after) - try validateAssembly(output, expected: block) - let previous = oldBlock.map { document.normalized($0) } - return InstructionAssembly( - bytes: document.byteOrderMark + Data(output.utf8), headingOffset: offset, block: block, - blockHash: hash(Data(block.utf8)), - adoptedSections: adopted, conflicts: conflicts, - blockDifference: previous.flatMap { - $0.utf8.elementsEqual(block.utf8) ? nil : difference(from: $0, to: block) - }, - hasCustomContent: !before.isEmpty || !after.isEmpty) + return common.joined(separator: "/") } - /// Removes the entire block and its adjacent separating blanks, retaining all other custom bytes - /// except trailing blank lines and the final line ending, which become a single LF. - public static func remove(from bytes: Data) throws -> InstructionAssembly { - let document = try MarkdownDocument(bytes: bytes) - guard let block = try document.managedBlock() else { - return InstructionAssembly( - bytes: bytes, headingOffset: 0, block: nil, blockHash: nil, adoptedSections: [], - conflicts: [], - blockDifference: nil, hasCustomContent: !document.lines.isEmpty) + /// Renders a generated target: the notice, then the sections in order, one blank line apart. + /// The result is parsed again; every section's first heading must stay a document heading. + public static func render(_ sections: [InstructionSection]) throws -> String { + guard !sections.isEmpty else { throw InstructionError.invalidAssembly } + try validateSelection(sections) + var lines = [notice, ""] + var expected: [(line: Int, level: Int)] = [] + for (index, section) in sections.enumerated() { + if index > 0 { lines.append("") } + expected.append((lines.count, section.level)) + lines += section.content.split(separator: "\n", omittingEmptySubsequences: false).map( + String.init) } - var lower = block.lowerBound - var upper = block.upperBound - if lower > 0, document.lines[lower - 1].isBlank { lower -= 1 } - if upper < document.lines.count, document.lines[upper].isBlank { upper += 1 } - var custom = Array(document.lines[.. InstructionDrift { - var baseline: String? - if let lockedBlock { - let expected = MarkdownDocument(lockedBlock) - guard let range = try expected.managedBlock(), range == 0.. Bool { + var text = String(decoding: bytes, as: UTF8.self) + if text.first == "\u{FEFF}" { text.removeFirst() } + return MarkdownLine.parse(text).first?.text == notice } - /// Source headings are retained. Custom text is appended verbatim after one separating blank line. + /// Sections render as in targets, without the notice. Custom text follows after one blank line. public static func renderChatGPT( sections: [InstructionSection], customContent: Data? = nil ) throws -> Data { @@ -185,6 +120,63 @@ public enum Instructions { return output } + /// Links, images and reference definitions with local destinations, and raw HTML links, outside + /// code. URLs with a scheme other than `file:` and bare fragments are omitted. + public static func localLinks(in text: String) -> [InstructionLink] { + var result: [InstructionLink] = [] + func add(_ kind: InstructionLink.Kind, _ destination: String) { + if let path = localPath(destination) { + result.append(InstructionLink(kind: kind, destination: destination, path: path)) + } + } + let document = Document(parsing: text, options: [.disableSmartOpts]) + var code = IndexSet() + var pending: [Markup] = [document] + while let node = pending.popLast() { + if let link = node as? Link { + add(.link, link.destination ?? "") + } else if let image = node as? Image { + add(.image, image.source ?? "") + } + let html = (node as? InlineHTML)?.rawHTML ?? (node as? HTMLBlock)?.rawHTML + if let html, html.range(of: #"(?i)\b(href|src)\s*="#, options: .regularExpression) != nil { + result.append(InstructionLink(kind: .html, destination: html, path: nil)) + } + if node is CodeBlock || node is HTMLBlock, let range = node.range { + code.insert(integersIn: (range.lowerBound.line - 1)..\n]*>|\S+)"#) + for (index, line) in MarkdownLine.parse(text).enumerated() where !code.contains(index) { + let range = NSRange(line.text.startIndex..., in: line.text) + guard let match = definition.firstMatch(in: line.text, range: range), + let value = Range(match.range(at: 1), in: line.text) + else { continue } + var destination = String(line.text[value]) + if destination.hasPrefix("<") { destination = String(destination.dropFirst().dropLast()) } + add(.definition, destination) + } + return result + } + + /// The decoded path of a local destination, or nil for a fragment or a non-file URL. + /// An empty destination is local and yields an empty path. + static func localPath(_ destination: String) -> String? { + let value = destination.trimmingCharacters(in: .whitespaces) + if value.hasPrefix("#") { return nil } + if let scheme = value.range(of: #"^[A-Za-z][A-Za-z0-9+.-]*:"#, options: .regularExpression) { + guard value[scheme].lowercased() == "file:" else { return nil } + return URL(string: value)?.path ?? "" + } + let end = value.firstIndex { $0 == "?" || $0 == "#" } ?? value.endIndex + let path = String(value[.. [String] { let installed = Set(user) @@ -192,8 +184,52 @@ public enum Instructions { return project.filter { installed.contains($0) && seen.insert($0).inserted } } + /// Compares the managed block of a Claude file with its locked hash. + public static func detectDrift(in bytes: Data, lockedBlockHash: String) throws + -> InstructionDrift + { + let document = try MarkdownDocument(bytes: bytes) + guard let range = try document.managedBlock() else { return .missing } + let actual = document.normalized(range) + return hash(Data(actual.utf8)) == lockedBlockHash ? .clean : .drifted + } + static func hash(_ bytes: Data) -> String { "sha256:" + FileHash.sha256Hex(data: bytes) } + static func patternProblem(_ pattern: String) -> String? { + guard !pattern.isEmpty, !pattern.hasPrefix("/") else { return "must be project-relative." } + guard !pattern.contains(where: { "\\`[]{}\0".contains($0) }) else { + return "may use only the wildcards '*', '**' and '?'." + } + let segments = pattern.split(separator: "/", omittingEmptySubsequences: false) + for segment in segments { + if segment.isEmpty || segment == "." || segment == ".." { + return "must not have empty, '.' or '..' segments." + } + if segment.contains("**"), segment != "**" { return "may use '**' only as a whole segment." } + } + return nil + } + + /// Removes a Claude file's managed block and its adjacent separating blanks, retaining other + /// bytes except trailing blank lines and the final line ending, which become a single LF. + static func removeBlock(from bytes: Data) throws -> (bytes: Data, hasCustomContent: Bool) { + let document = try MarkdownDocument(bytes: bytes) + guard let block = try document.managedBlock() else { + return (bytes, !document.lines.isEmpty) + } + var lower = block.lowerBound + var upper = block.upperBound + if lower > 0, document.lines[lower - 1].isBlank { lower -= 1 } + if upper < document.lines.count, document.lines[upper].isBlank { upper += 1 } + var custom = Array(document.lines[.. Bool { + line.allSatisfy { $0 == " " || $0 == "\t" } + } + private static func validateSelection(_ sections: [InstructionSection]) throws { - let byHeading = Dictionary(grouping: sections, by: \.heading) + let byHeading = Dictionary(grouping: sections) { "\($0.level) \($0.heading)" } for section in sections { - if let duplicates = byHeading[section.heading], duplicates.count > 1 { + if let duplicates = byHeading["\(section.level) \(section.heading)"], duplicates.count > 1 { throw InstructionError.duplicateHeading( heading: section.heading, sectionIDs: duplicates.map(\.id)) } } } - private static func render(_ section: InstructionSection, offset: Int) throws -> String { - var lines = section.document.lines.map(\.text) - for heading in section.document.headings { - guard heading.level + offset <= 6 else { - throw InstructionError.headingOverflow( - sectionID: section.id, level: heading.level, offset: offset) - } - let line = heading.lines.lowerBound - let index = lines[line].utf8.index( - lines[line].utf8.startIndex, offsetBy: heading.openingOffset!) - lines[line].insert(contentsOf: String(repeating: "#", count: offset), at: index) - } - return lines.joined(separator: "\n") - } - - static func difference(from old: String, to new: String) -> String { - let before = MarkdownLine.parse(old).map(\.text) - let after = MarkdownLine.parse(new).map(\.text) - let changes = after.map { Data($0.utf8) }.difference(from: before.map { Data($0.utf8) }) - var removed: Set = [] - var inserted: Set = [] - for change in changes { - switch change { - case .remove(let offset, _, _): removed.insert(offset) - case .insert(let offset, _, _): inserted.insert(offset) - } - } - var output = [ - "--- existing", "+++ proposed", - "@@ -\(before.isEmpty ? 0 : 1),\(before.count) +\(after.isEmpty ? 0 : 1),\(after.count) @@", - ] - var left = 0 - var right = 0 - while left < before.count || right < after.count { - if removed.contains(left) { - output.append("-" + before[left]) - left += 1 - } else if inserted.contains(right) { - output.append("+" + after[right]) - right += 1 - } else { - output.append(" " + before[left]) - left += 1 - right += 1 - } - } - if !old.isEmpty, old.utf8.last != 10, old.utf8.last != 13 { - output.append("\\ No newline at end of existing text") - } - if !new.isEmpty, new.utf8.last != 10, new.utf8.last != 13 { - output.append("\\ No newline at end of proposed text") - } - return output.joined(separator: "\n") + "\n" - } } diff --git a/Sources/AgentsInstructions/MarkdownDocument.swift b/Sources/AgentsInstructions/MarkdownDocument.swift index 57ea261..43aa9f8 100644 --- a/Sources/AgentsInstructions/MarkdownDocument.swift +++ b/Sources/AgentsInstructions/MarkdownDocument.swift @@ -43,17 +43,6 @@ struct MarkdownHeading: Sendable, Equatable { var key: String { text.split(whereSeparator: \.isWhitespace).joined(separator: " ") } } -struct HeadingIdentity: Hashable, Sendable { - let level: Int - let text: String -} - -struct MarkdownSection: Sendable, Equatable { - let headingLine: Int - /// Physical ranges omit reference definitions consumed before Setext headings. - let contentRanges: [Range] -} - struct MarkdownDocument: Sendable, Equatable { static let begin = "" @@ -64,8 +53,6 @@ struct MarkdownDocument: Sendable, Equatable { var headings: [MarkdownHeading] = [] var topLevelHeadings: [MarkdownHeading] = [] var markers: [Int] = [] - var sections: [HeadingIdentity: [MarkdownSection]] = [:] - private var referenceDefinitionLines: Set = [] var endsInCode = false var endsInHTML = false @@ -93,7 +80,6 @@ struct MarkdownDocument: Sendable, Equatable { } else if topLevel { let contentStart = firstContentLine( afterDefinitionsAt: first, before: min(range.upperBound.line, lines.count)) - referenceDefinitionLines.formUnion(first..) -> String { - var trimmed = lines - while trimmed.last?.isBlank == true { trimmed = trimmed.dropLast() } - return trimmed.map(\.text).joined(separator: "\n") - } - /// Physical prefix verification is used only for blocks already identified by CommonMark. private static func contentOffset(in bytes: [UInt8], inContainer: Bool) -> Int { var cursor = 0 @@ -221,33 +200,6 @@ struct MarkdownDocument: Sendable, Equatable { return contentStart } - private mutating func indexSections() { - var nextAtLevel = Array(repeating: lines.count, count: 7) - var markerIndex = markers.count - var nextMarker = lines.count - var ranges: [Range] = [] - for heading in topLevelHeadings.reversed() { - while markerIndex > 0, markers[markerIndex - 1] > heading.lines.lowerBound { - markerIndex -= 1 - nextMarker = markers[markerIndex] - } - let end = min(nextAtLevel[1...heading.level].min()!, nextMarker) - ranges.append(heading.lines.lowerBound..] = [] - var start = range.lowerBound - for line in range where referenceDefinitionLines.contains(line) { - if start < line { contentRanges.append(start.. Markup { var node = document while node is Document || node is BlockQuote || node is ListItem || node is ListItemContainer { diff --git a/Tests/AgentsCoreTests/InstructionTransactionTests.swift b/Tests/AgentsCoreTests/InstructionTransactionTests.swift index f033f98..e3ca039 100644 --- a/Tests/AgentsCoreTests/InstructionTransactionTests.swift +++ b/Tests/AgentsCoreTests/InstructionTransactionTests.swift @@ -57,6 +57,19 @@ struct InstructionTransactionTests { #expect(throws: (any Error).self) { try paths.components("instructions-project/other.md") } #expect(throws: (any Error).self) { try paths.components("instructions-project/../AGENTS.md") } #expect(throws: (any Error).self) { try paths.components("instructions-codex/AGENTS.md") } + #expect(throws: (any Error).self) { + try paths.components("instructions-project/.git/AGENTS.md") + } + #expect(throws: (any Error).self) { + try paths.components("instructions-project/.agent/instructions/AGENTS.md") + } + #expect(throws: (any Error).self) { + try paths.components("instructions-project/Sources/CLAUDE.md") + } + #expect(throws: Never.self) { + try paths.components("instructions-project/Sources/Render/AGENTS.md") + } + #expect(throws: Never.self) { try paths.components("instructions-project/Sources/GEMINI.md") } let outside = root.appendingPathComponent("outside") try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) try Data("owner".utf8).write(to: outside.appendingPathComponent("CLAUDE.md")) diff --git a/Tests/AgentsCoreTests/StateModelTests.swift b/Tests/AgentsCoreTests/StateModelTests.swift index 1e9e3e4..05758e2 100644 --- a/Tests/AgentsCoreTests/StateModelTests.swift +++ b/Tests/AgentsCoreTests/StateModelTests.swift @@ -5,6 +5,56 @@ import Testing @Suite("Declared state") struct StateModelTests { + @Test func validatesOwnInstructionRecordsAndReferences() throws { + let digest = "sha256:" + String(repeating: "a", count: 64) + func lock(_ section: LockedSection) -> ResolvedState { + ResolvedState(instructions: LockedInstructions(sections: [section])) + } + #expect(throws: Never.self) { + try lock( + LockedSection( + name: "guide", source: ".", path: ".agent/instructions/guide.md", hash: digest) + ) + .validate() + } + #expect(throws: (any Error).self) { + try lock( + LockedSection( + name: "guide", source: ".", revision: String(repeating: "b", count: 40), + path: ".agent/instructions/guide.md", hash: digest) + ).validate() + } + #expect(throws: (any Error).self) { + try lock(LockedSection(name: "guide", source: ".", path: "guide.md", hash: digest)).validate() + } + #expect(throws: (any Error).self) { + try lock( + LockedSection( + name: "Guide", source: ".", path: ".agent/instructions/Guide.md", hash: digest) + ) + .validate() + } + let environment = RuntimeEnvironment( + projectDirectory: URL(fileURLWithPath: "/project"), + homeDirectory: URL(fileURLWithPath: "/home"), + environment: [:]) + let source = SourceDeclaration(kind: .git, location: "github.com/owner/repo") + for references in [["guide"], ["epd/review", "rules:auto-review/swift"]] { + #expect(throws: Never.self) { + try Declaration( + sources: ["rules": source], instructions: InstructionsDeclaration(sections: references) + ).validate(environment: environment) + } + } + for reference in ["Guide", "rules:Review", "missing:review", "rules:", "a//b", "a:b:c"] { + #expect(throws: (any Error).self) { + try Declaration( + sources: ["rules": source], instructions: InstructionsDeclaration(sections: [reference]) + ).validate(environment: environment) + } + } + } + @Test func roundTripsCompleteStateDeterministically() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } diff --git a/Tests/AgentsCoreTests/WatchDurabilityTests.swift b/Tests/AgentsCoreTests/WatchDurabilityTests.swift index e0fa155..b651a3e 100644 --- a/Tests/AgentsCoreTests/WatchDurabilityTests.swift +++ b/Tests/AgentsCoreTests/WatchDurabilityTests.swift @@ -157,7 +157,7 @@ final class WatchGitFixture { do { try FileManager.default.createDirectory( at: repo.appendingPathComponent("instructions"), withIntermediateDirectories: true) - try Data("# Rule\ninitial\n".utf8).write( + try Data("---\ndescription: Fixture instructions.\n---\n# Rule\ninitial\n".utf8).write( to: repo.appendingPathComponent("instructions/rule.md")) try initGitRepo(repo) try store.save( @@ -179,7 +179,7 @@ final class WatchGitFixture { try git(["rm", "-rf", "."]) try FileManager.default.createDirectory( at: repo.appendingPathComponent("instructions"), withIntermediateDirectories: true) - try Data("# Rule\n\(name)\n".utf8).write( + try Data("---\ndescription: Fixture instructions.\n---\n# Rule\n\(name)\n".utf8).write( to: repo.appendingPathComponent("instructions/rule.md")) try git(["add", "."]) try git(["commit", "-m", name]) diff --git a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift index ac8c1a0..c7713e9 100644 --- a/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift +++ b/Tests/AgentsCoreTests/WatchMirrorConcurrencyTests.swift @@ -65,7 +65,7 @@ struct WatchMirrorConcurrencyTests { try #require(!exists(scopeLock)) try FileManager.default.removeItem( at: fixture.root.appendingPathComponent("listing-finished")) - try Data("# Rule\nupdated\n".utf8).write( + try Data("---\ndescription: Fixture instructions.\n---\n# Rule\nupdated\n".utf8).write( to: fixture.repo.appendingPathComponent("instructions/rule.md")) try fixture.git(["commit", "-am", "update"]) } diff --git a/Tests/AgentsInstructionsTests/AssemblyTests.swift b/Tests/AgentsInstructionsTests/AssemblyTests.swift deleted file mode 100644 index de66da6..0000000 --- a/Tests/AgentsInstructionsTests/AssemblyTests.swift +++ /dev/null @@ -1,339 +0,0 @@ -import AgentsInstructions -import Foundation -import Testing - -@Suite("Instruction assembly") -struct InstructionAssemblyTests { - @Test func declaresSectionOrderAndKeepsSubsections() throws { - let sections = try [ - source("# First\na\n\n## Child\nb\n"), source("# Second\nc\n", id: "other"), - ] - let result = try Instructions.assemble(Data(), sections: sections) - #expect(result.block == block("# First\na\n\n## Child\nb\n\n# Second\nc")) - #expect(!result.hasCustomContent) - } - - @Test func sectionStopsAtSameOrHigherHeading() throws { - let target = "# Rules\nUse care.\n\n# Other\nKeep exactly.\n" - let result = try Instructions.assemble( - Data(target.utf8), sections: [source()], options: .init(headingOffset: 0)) - #expect(result.adoptedSections == ["rules:care"]) - #expect(text(result) == block("# Rules\nUse care.") + "\n# Other\nKeep exactly.\n") - } - - @Test func lowerHeadingBelongsToMatchedSection() throws { - let target = "# Rules\nUse care.\n\n## Custom child\nOwned by the section.\n" - #expect(throws: InstructionError.self) { - try Instructions.assemble(Data(target.utf8), sections: [source()]) - } - } - - @Test func replacesExistingContiguousBlockInPlace() throws { - let target = "Before\n\n" + block("# Old\nOld text.") + "\n# After\nKeep\n" - let result = try Instructions.assemble(Data(target.utf8), sections: [source()]) - #expect(text(result) == "Before\n\n" + block("# Rules\nUse care.") + "\n# After\nKeep\n") - #expect(result.blockDifference?.contains("-Old text.") == true) - } - - @Test(arguments: [ - beginMarker, endMarker, beginMarker + "\n" + beginMarker + "\n" + endMarker, - block("# One") + block("# Two"), endMarker + "\n" + beginMarker, - ]) - func rejectsMalformedMarkers(_ target: String) { - #expect(throws: InstructionError.self) { - try Instructions.assemble(Data(target.utf8), sections: [source()]) - } - #expect(throws: InstructionError.self) { try Instructions.remove(from: Data(target.utf8)) } - } - - @Test func markerErrorsIncludeLocations() { - #expect(throws: InstructionError.unpairedMarker(line: 2)) { - try Instructions.remove(from: Data("text\n\(endMarker)\n".utf8)) - } - #expect(throws: InstructionError.nestedMarker(line: 2)) { - try Instructions.remove(from: Data("\(beginMarker)\n\(beginMarker)\n".utf8)) - } - #expect(throws: InstructionError.multipleBlocks) { - try Instructions.remove(from: Data((block("a") + block("b")).utf8)) - } - } - - @Test func targetCodeMarkersAndHeadingsAreIgnored() throws { - let custom = - "```\n# Fake title\n\(beginMarker)\n```\n\n # Fake title\n \(endMarker)\n\nEnd\n" - let result = try Instructions.assemble(Data(custom.utf8), sections: [source()]) - #expect(result.headingOffset == 0) - #expect(text(result) == block("# Rules\nUse care.") + "\n" + custom) - } - - @Test func titleShiftsHeadings() throws { - let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [source()]) - #expect(result.headingOffset == 1) - #expect(result.block == block("## Rules\nUse care.")) - } - - @Test func selectedOnlyH1IsAdoptedWithoutOffset() throws { - let result = try Instructions.assemble(Data("# Rules\nUse care.\n".utf8), sections: [source()]) - #expect(result.headingOffset == 0) - #expect(result.adoptedSections == ["rules:care"]) - #expect(text(result) == block("# Rules\nUse care.")) - #expect(!result.hasCustomContent) - } - - @Test func titleAfterBlockDoesNotShift() throws { - let result = try Instructions.assemble( - Data((block("# Old") + "\n# Later\n").utf8), sections: [source()]) - #expect(result.headingOffset == 0) - } - - @Test func titleAppearanceAndDisappearanceRecomputeOffset() throws { - let initial = try Instructions.assemble(Data(), sections: [source()]) - let withTitle = try Instructions.assemble( - Data(("# Guide\n\n" + text(initial)).utf8), sections: [source()]) - #expect(withTitle.headingOffset == 1) - let withoutTitle = try Instructions.assemble( - Data(try #require(withTitle.block).utf8), sections: [source()]) - #expect(withoutTitle.headingOffset == 0) - #expect(withoutTitle.bytes == initial.bytes) - } - - @Test func installUsesLockedOffset() throws { - let withTitle = try Instructions.assemble( - Data("# Guide\n".utf8), sections: [source()], options: .init(headingOffset: 0)) - #expect(withTitle.headingOffset == 0) - #expect(withTitle.block == block("# Rules\nUse care.")) - let withoutTitle = try Instructions.assemble( - Data(), sections: [source()], options: .init(headingOffset: 1)) - #expect(withoutTitle.block == block("## Rules\nUse care.")) - #expect( - try Instructions.assemble( - withoutTitle.bytes, sections: [source()], options: .init(headingOffset: 1) - ).bytes == withoutTitle.bytes) - } - - @Test func levelSixIsValidWithoutShiftAndOverflowsWithTitle() throws { - let section = try source("# Rules\n\n###### Deep\nBody\n") - #expect(try Instructions.assemble(Data(), sections: [section]).headingOffset == 0) - #expect(throws: InstructionError.headingOverflow(sectionID: section.id, level: 6, offset: 1)) { - try Instructions.assemble(Data("# Guide\n".utf8), sections: [section]) - } - } - - @Test(arguments: [-1, 2, Int.max]) - func rejectsInvalidOffset(_ offset: Int) { - #expect(throws: InstructionError.invalidHeadingOffset(offset)) { - try Instructions.assemble(Data(), sections: [source()], options: .init(headingOffset: offset)) - } - } - - @Test func matchingCollapsesWhitespaceAndTrimsClosingHashes() throws { - let result = try Instructions.assemble( - Data("# Guide\n\n## Be \t careful ###\nOld\n".utf8), - sections: [source("# Be careful\nNew\n")], options: .init(replaceConflicts: true)) - #expect(result.conflicts.count == 1) - #expect(result.conflicts.first?.existing.hasPrefix("## Be") == true) - #expect(!text(result).contains("Old")) - } - - @Test func matchingRequiresLevelAndCase() throws { - let target = "# Guide\n\n### Rules\nKeep\n\n## rules\nKeep also\n" - let result = try Instructions.assemble(Data(target.utf8), sections: [source()]) - #expect(result.adoptedSections.isEmpty) - #expect(result.conflicts.isEmpty) - #expect(text(result).hasSuffix("### Rules\nKeep\n\n## rules\nKeep also\n")) - } - - @Test func rejectsAmbiguousCustomMatches() { - #expect(throws: InstructionError.ambiguousMatch(sectionID: "rules:care", lines: [3, 6])) { - try Instructions.assemble( - Data("# Guide\n\n## Rules\na\n\n## Rules\nb\n".utf8), sections: [source()]) - } - } - - @Test func rejectsDuplicateSelectedHeadingsAcrossSources() { - #expect( - throws: InstructionError.duplicateHeading( - heading: "Rules", sectionIDs: ["one:rules", "two:rules"]) - ) { - try Instructions.assemble( - Data(), - sections: [source(id: "one:rules"), source("# Rules ###\nOther\n", id: "two:rules")]) - } - } - - @Test func placesAtEarliestMatchAndUsesDeclaredOrder() throws { - let target = "# Guide\n\n## Second\nb\n\n## Custom\nKeep\n\n## First\na\n" - let result = try Instructions.assemble( - Data(target.utf8), sections: [source("# First\na\n"), source("# Second\nb\n", id: "second")]) - #expect( - text(result) == "# Guide\n\n" + block("## First\na\n\n## Second\nb") + "\n## Custom\nKeep\n\n" - ) - #expect(result.adoptedSections == ["rules:care", "second"]) - } - - @Test func placesAfterTitleBeforeFirstHeading() throws { - let target = "# Guide\nIntro.\n\n## Custom\nKeep\n" - let result = try Instructions.assemble(Data(target.utf8), sections: [source()]) - #expect( - text(result) == "# Guide\nIntro.\n\n" + block("## Rules\nUse care.") + "\n## Custom\nKeep\n") - } - - @Test func appendsToFileWithOnlyTitle() throws { - let result = try Instructions.assemble(Data("# Guide\nIntro.".utf8), sections: [source()]) - #expect(text(result) == "# Guide\nIntro.\n\n" + block("## Rules\nUse care.")) - } - - @Test func prependsWithoutTitle() throws { - let target = "Preamble\n\n## Custom\nKeep" - let result = try Instructions.assemble(Data(target.utf8), sections: [source()]) - #expect(text(result) == block("# Rules\nUse care.") + "\n" + target) - } - - @Test func reportsConflictsWithBothTextsAndDifference() throws { - do { - _ = try Instructions.assemble(Data("# Rules\nOld\n".utf8), sections: [source()]) - Issue.record("Expected a conflict") - } catch InstructionError.conflictingSections(let conflicts) { - let conflict = try #require(conflicts.first) - #expect(conflict.existing == "# Rules\nOld") - #expect(conflict.proposed == "# Rules\nUse care.") - #expect(conflict.difference.contains("-Old\n+Use care.")) - #expect( - InstructionError.conflictingSections(conflicts).description.contains(conflict.difference)) - } - } - - @Test func replacementReturnsConflictsForCallerPreview() throws { - let result = try Instructions.assemble( - Data("# Rules\nOld\n".utf8), sections: [source()], options: .init(replaceConflicts: true)) - #expect(result.conflicts.count == 1) - #expect(result.adoptedSections.isEmpty) - #expect(text(result) == block("# Rules\nUse care.")) - } - - @Test func adoptsNormalizedIdenticalContent() throws { - let result = try Instructions.assemble( - Data("# Rules\r\nUse care.\r\n\r\n".utf8), sections: [source()]) - #expect(result.adoptedSections == ["rules:care"]) - #expect(result.conflicts.isEmpty) - #expect(text(result) == block("# Rules\nUse care.")) - } - - @Test func preservesCustomCRLFAndNormalizesOwnedRegion() throws { - let target = - "# Guide\r\n\r\n" + block("## Old\nOld").replacingOccurrences(of: "\n", with: "\r\n") - + "\r\n## Custom\r\nBytes \r\n\r\n" - let result = try Instructions.assemble(Data(target.utf8), sections: [source()]) - #expect( - text(result) == "# Guide\r\n\n" + block("## Rules\nUse care.") - + "\n## Custom\r\nBytes \r\n\r\n") - } - - @Test func preservesExtraCustomBlankLines() throws { - let target = "Before\r\n\r\n\r\n" + block("# Old") + "\r\n\r\nAfter\r\n" - let result = try Instructions.assemble(Data(target.utf8), sections: [source()]) - #expect(text(result) == "Before\r\n\r\n\n" + block("# Rules\nUse care.") + "\n\r\nAfter\r\n") - #expect(try Instructions.assemble(result.bytes, sections: [source()]).bytes == result.bytes) - } - - @Test func rejectsAssemblyWhoseMarkersAreSwallowedByCode() { - #expect(throws: InstructionError.invalidAssembly) { - try Instructions.assemble(Data("# Guide\n\n```\nUnclosed\n".utf8), sections: [source()]) - } - } - - @Test(arguments: [ - "", "# Guide\n", "Custom\r\n", "# Rules\nUse care.\n", "Guide\n=====\n\n## Custom\nX\n", - ]) - func assemblyIsIdempotent(_ target: String) throws { - let first = try Instructions.assemble(Data(target.utf8), sections: [source()]) - let second = try Instructions.assemble(first.bytes, sections: [source()]) - #expect(second.bytes == first.bytes) - #expect(second.blockHash == first.blockHash) - #expect(second.blockDifference == nil) - } - - @Test func recognizesSetextTitle() throws { - let result = try Instructions.assemble( - Data("Project Guide\n=============\nIntro\n\nCustom\n------\nKeep\n".utf8), - sections: [source()]) - #expect(result.headingOffset == 1) - #expect( - text(result) == "Project Guide\n=============\nIntro\n\n" + block("## Rules\nUse care.") - + "\nCustom\n------\nKeep\n") - } - - @Test func setextSelectedHeadingIsAMatchRatherThanTitle() throws { - let result = try Instructions.assemble( - Data("Rules\n=====\nUse care.\n".utf8), sections: [source()], - options: .init(replaceConflicts: true)) - #expect(result.headingOffset == 0) - #expect(result.conflicts.count == 1) - #expect(!result.hasCustomContent) - } - - @Test func removesLastSectionAndSeparators() throws { - let target = "# Guide\r\n\r\n" + block("## Rules\nUse care.") + "\r\n## Custom\r\nKeep\r\n\r\n" - let result = try Instructions.remove(from: Data(target.utf8)) - #expect(text(result) == "# Guide\r\n## Custom\r\nKeep\n") - #expect(result.block == nil) - #expect(result.blockHash == nil) - #expect(result.hasCustomContent) - #expect(try Instructions.assemble(Data(target.utf8), sections: []).bytes == result.bytes) - } - - @Test func removingOnlyBlockLeavesNoCustomContent() throws { - let result = try Instructions.remove(from: Data(block("# Rules\nUse care.").utf8)) - #expect(result.bytes.isEmpty) - #expect(!result.hasCustomContent) - } - - @Test func removalWithoutBlockPreservesBytes() throws { - let custom = Data("Custom\r\n\r\n".utf8) - #expect(try Instructions.remove(from: custom).bytes == custom) - #expect(try Instructions.remove(from: custom).hasCustomContent) - } - - @Test func removingSomeSectionsKeepsBlock() throws { - let initial = try Instructions.assemble( - Data(), sections: [source(), source("# Other\nX\n", id: "other")]) - let result = try Instructions.assemble(initial.bytes, sections: [source()]) - #expect(result.block == block("# Rules\nUse care.")) - #expect(!result.hasCustomContent) - } - - @Test func reportsOnlySharedSourceQualifiedScopeIdentities() { - #expect( - Instructions.sectionsInBothScopes( - user: ["one:rules", "two:other"], project: ["two:other", "one:rules", "one:rules"]) == [ - "two:other", "one:rules", - ]) - #expect(Instructions.sectionsInBothScopes(user: ["one:rules"], project: ["two:rules"]).isEmpty) - #expect(Instructions.sectionsInBothScopes(user: [], project: ["one:rules"]).isEmpty) - } - @Test func rejectsAssemblyWhoseMarkersAreSwallowedByHTML() throws { - #expect(throws: InstructionError.invalidAssembly) { - try Instructions.assemble(Data("# Guide\n\n" +let endMarker = "" + +func block(_ content: String) -> String { + beginMarker + "\n" + content + "\n" + endMarker + "\n" +} + +@Suite("Claude forwarding") +struct ClaudeForwardingTests { + @Test(arguments: ClaudeInstructionPath.allCases) + func rendersRelativeImportBlock(_ path: ClaudeInstructionPath) throws { + let expected = path == .directory ? "@../AGENTS.md" : "@AGENTS.md" + let rendered = ClaudeForwarding.renderBlock(for: path) + #expect(rendered == block(expected)) + #expect(try ClaudeForwarding.containsImport(in: Data(rendered.utf8), at: path)) + } + + @Test(arguments: ["@AGENTS.md", "@./AGENTS.md", "@rules/../AGENTS.md"]) + func recognizesEquivalentImport(_ line: String) throws { + #expect( + try ClaudeForwarding.containsImport(in: Data(("# Guide\n\n" + line + "\n").utf8), at: .root)) + } + + @Test(arguments: ["@AGENTS.md", "@../../AGENTS.md", "@\"../AGENTS.md\"", "@../AGENTS.md/"]) + func rejectsWrongDirectoryImport(_ line: String) throws { + #expect(try !ClaudeForwarding.containsImport(in: Data(line.utf8), at: .directory)) + } + + @Test func ignoresImportsInsideCode() throws { + let target = "```\n@AGENTS.md\n```\n\n @AGENTS.md\n" + #expect(try !ClaudeForwarding.containsImport(in: Data(target.utf8), at: .root)) + } + + @Test func rootSymlinkAlreadyForwards() throws { + let files = [ClaudeInstructionFile(path: .root, isSymbolicLinkToAgents: true)] + #expect(try ClaudeForwarding.classify(files) == .forwarding(.root)) + #expect(try ClaudeForwarding.classify([.init(path: .root)]) == .needsImport(.root)) + } + + @Test func choosesFirstExistingClaudeFile() throws { + #expect( + try ClaudeForwarding.classify([ + .init(path: .local), .init(path: .directory), .init(path: .root), + ]) == .needsImport(.root)) + #expect( + try ClaudeForwarding.classify([.init(path: .local), .init(path: .directory)]) + == .needsImport(.directory)) + #expect(try ClaudeForwarding.classify([.init(path: .local)]) == .needsImport(.local)) + #expect(try ClaudeForwarding.classify([]) == .automatic) + } + + @Test func existingImportInAnotherProjectFileForwards() throws { + let files = [ + ClaudeInstructionFile(path: .root), + ClaudeInstructionFile(path: .directory, bytes: Data("@../AGENTS.md\n".utf8)), + ] + #expect(try ClaudeForwarding.classify(files) == .forwarding(.directory)) + } + + @Test func rejectsMalformedForwardingMarkers() { + #expect(throws: InstructionError.self) { + try ClaudeForwarding.containsImport( + in: Data((beginMarker + "\n@AGENTS.md\n").utf8), at: .root) + } + } +} + +@Suite("Standalone Claude forwarding") +struct StandaloneClaudeForwardingTests { + @Test(arguments: [ + "**@AGENTS.md**/backup", "\"**@AGENTS.md**\"", "**@AGENTS.md**", "See @AGENTS.md", + "@AGENTS.md other", "\"@AGENTS.md\"", "@\"AGENTS.md\"", "> @AGENTS.md", "- @AGENTS.md", + "@**folder**/../AGENTS.md", "@AGENTS.md/backup", "@AGENTS.md\n===\n", + "**start\n@AGENTS.md\nend**\n", "`start\n@AGENTS.md\nend`\n", + "\n", "[ref]: /url \"title\n@AGENTS.md\nend\"\n", + ]) + func requiresManagedImportForMentionsAndExamples(_ content: String) throws { + let bytes = Data(content.utf8) + #expect(try !ClaudeForwarding.containsImport(in: bytes, at: .root)) + #expect( + try ClaudeForwarding.classify([.init(path: .root, bytes: bytes)]) == .needsImport(.root)) + } + + @Test(arguments: [ + "@AGENTS.md", " @AGENTS.md \t", "@./AGENTS.md", "@rules/../AGENTS.md\n", + "@Design\\ Docs/../AGENTS.md", "P with `code`\n@AGENTS.md\n", + "[ref]: /url\n@AGENTS.md\n", "P\r\n@AGENTS.md\r", "P\n\t@AGENTS.md\n", + "agents-forwarding-line-0\n@AGENTS.md\n", + ]) + func recognizesStandaloneImportLines(_ content: String) throws { + #expect(try ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) + } + + @Test(arguments: ["@../AGENTS.md", " @.././AGENTS.md \t", "@../Design\\ Docs/../AGENTS.md"]) + func recognizesStandaloneDirectoryRelativeImports(_ content: String) throws { + #expect(try ClaudeForwarding.containsImport(in: Data(content.utf8), at: .directory)) + } + + @Test func standaloneCodeLineCannotBorrowProseImport() throws { + let content = "See @AGENTS.md\n\n```\n@AGENTS.md\n```\n" + #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) + } + + @Test func managedBlockForwardsAlongsideProseMentions() throws { + let content = "**@AGENTS.md**/backup\n\n" + ClaudeForwarding.renderBlock(for: .root) + #expect(try ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) + } +} + +@Suite("Claude import syntax") +struct ClaudeImportSyntaxTests { + @Test func quotedPathDoesNotForward() throws { + #expect( + try ClaudeForwarding.classify([.init(path: .root, bytes: Data("@\"AGENTS.md\"".utf8))]) + == .needsImport(.root)) + } + + @Test func proseImportNeedsManagedImport() throws { + #expect( + try ClaudeForwarding.classify([.init(path: .root, bytes: Data("See @AGENTS.md".utf8))]) + == .needsImport(.root)) + } + + @Test(arguments: [ + "See @../AGENTS.md", "@../AGENTS.md other", "- Read @.././AGENTS.md", + "See @../Design\\ Docs/../AGENTS.md", + ]) + func proseDirectoryRelativeTokensNeedManagedImport(_ content: String) throws { + #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .directory)) + } + + @Test(arguments: [ + "`@AGENTS.md`", "See `` @AGENTS.md ``", "See `first\n@AGENTS.md`", "```\n@AGENTS.md\n```", + " @AGENTS.md\n", "- item\n ```\n @AGENTS.md\n ```", "> ```\n> @AGENTS.md\n> ```", + "@'AGENTS.md'", "\"@AGENTS.md\"", "contact@AGENTS.md", + ]) + func ignoresCodeAndQuotedPaths(_ content: String) throws { + #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) + } + + @Test func inlineImportAfterCodeSpanNeedsManagedImport() throws { + let content = "Rüles\r\n`@wrong.md` then @AGENTS.md\r" + #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) + } + + @Test func proseWithUnterminatedBacktickNeedsManagedImport() throws { + #expect( + try !ClaudeForwarding.containsImport(in: Data("See `literal and @AGENTS.md".utf8), at: .root)) + } +} + +@Suite("Claude import examples") +struct ClaudeImportExampleTests { + @Test(arguments: [ + "[ref]: /url\n`@AGENTS.md`\n", + "P\n `@AGENTS.md`\n", + "P\r\n `@AGENTS.md`\r", + "P\n\t\t\t\t\t\t\t\t\t\t\t\t`@AGENTS.md`\n", + "P\r\n\t\t\t\t\t\t\t\t\t\t\t\t`@AGENTS.md`\r", + ]) + func codeSpanNeverForwards(_ content: String) throws { + let bytes = Data(content.utf8) + #expect(try !ClaudeForwarding.containsImport(in: bytes, at: .root)) + #expect( + try ClaudeForwarding.classify([.init(path: .root, bytes: bytes)]) == .needsImport(.root)) + } + + @Test(arguments: [ + "[ref]: /url\n`example` and @AGENTS.md\n", + "P\n `example` and @AGENTS.md\n", + "P\r\n `example` and @AGENTS.md\r", + "**See @AGENTS.md**", "> Read @AGENTS.md", "- Read @AGENTS.md", + ]) + func proseTextNeedsManagedImport(_ content: String) throws { + #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) + #expect( + try ClaudeForwarding.classify([.init(path: .root, bytes: Data(content.utf8))]) + == .needsImport(.root)) + } + + @Test(arguments: [ + "", "\n@AGENTS.md\n\n", + "
\n@AGENTS.md\n
\n", "Read example", + "[ref]: /@AGENTS.md\nReference.\n", + ]) + func htmlAndReferenceDestinationsDoNotForward(_ content: String) throws { + #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) + } +} + +@Suite("Claude import byte order marks") +struct ClaudeImportByteOrderMarkTests { + let bom = Data([0xEF, 0xBB, 0xBF]) + + @Test func importParsingAcceptsByteOrderMark() throws { + #expect(try ClaudeForwarding.containsImport(in: bom + Data("@AGENTS.md\n".utf8), at: .root)) + #expect(try !ClaudeForwarding.containsImport(in: bom + Data("`@AGENTS.md`\n".utf8), at: .root)) + } +} diff --git a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift index 48a6e31..b20303f 100644 --- a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift @@ -29,7 +29,7 @@ struct InstructionDoctorTests { let healthy = try InstructionOperations.doctor( scope: healthyScope, environment: fixture.environment) #expect(healthy.diagnostics.filter { $0.kind == .pendingRecovery }.count == 1) - #expect(healthy.diagnostics.contains { $0.kind == .missingBlock && $0.path == healthyFile }) + #expect(healthy.diagnostics.contains { $0.kind == .missingTarget && $0.path == healthyFile }) #expect(!healthy.diagnostics.contains { $0.kind == .duplicateScope }) #expect(try fixture.snapshot() == before) } @@ -93,7 +93,7 @@ struct InstructionDoctorTests { } }) let size = try #require(reports[0].diagnostics.first { $0.kind == .codexSize }) - #expect(size.message.contains("2050 bytes")) + #expect(size.message.contains("2048 bytes")) #expect(size.message.contains("(1536)")) #expect(!reports[1].diagnostics.contains { $0.kind == .codexSize }) #expect(try fixture.snapshot() == before) @@ -114,11 +114,11 @@ struct InstructionDoctorTests { runtime.projectDirectory = nested let report = try InstructionOperations.doctor(environment: runtime) #expect( - report.diagnostics.contains { $0.kind == .codexSize && $0.message.contains("1802 bytes") }) + report.diagnostics.contains { $0.kind == .codexSize && $0.message.contains("1800 bytes") }) #expect(!report.diagnostics.contains { $0.kind == .invalidConfiguration }) } - @Test func doctorReportsAdoptionsAndConflictsWithoutChangingCustomSections() throws { + @Test func doctorReportsForeignAndDriftedTargetsWithoutWriting() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() @@ -127,12 +127,12 @@ struct InstructionDoctorTests { try fixture.write("# rules\n\nOriginal\n", to: file) #expect( try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { - $0.kind == .adoption + $0.kind == .foreignTarget && $0.path == file }) - try fixture.write("# rules\n\nCustom\n", to: file) + try fixture.write(generated(["# rules\n\nCustom"]), to: file) let report = try InstructionOperations.doctor(environment: fixture.environment) - #expect(report.diagnostics.contains { $0.kind == .conflict && $0.message.contains("-Custom") }) - #expect(try fixture.text() == "# rules\n\nCustom\n") + #expect(report.diagnostics.contains { $0.kind == .drift && $0.path == file }) + #expect(try fixture.text() == generated(["# rules\n\nCustom"])) } @Test func diagnosesBothScopesOverridesAncestorsAndConfiguredByteLimit() throws { @@ -179,7 +179,7 @@ struct InstructionDoctorTests { let reports = InstructionOperations.doctor( projectRoots: [fixture.project, empty, pending], environment: fixture.environment) #expect(reports.count == 3) - #expect(reports[0].diagnostics.contains { $0.kind == .missingBlock }) + #expect(reports[0].diagnostics.contains { $0.kind == .missingTarget }) #expect(reports[2].diagnostics.map(\.kind) == [.pendingRecovery]) #expect(try fixture.snapshot() == before) #expect(!FileManager.default.fileExists(atPath: empty.appendingPathComponent(".agent").path)) @@ -188,7 +188,7 @@ struct InstructionDoctorTests { atPath: pending.appendingPathComponent(".agent/.agents.lock").path)) } - @Test func codexCountsOnlyLoadedChainAndSkipsEmptyOverrides() throws { + @Test func codexBudgetCountsOnlyTheProjectChainAndEmptyOverridesWin() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() @@ -201,25 +201,51 @@ struct InstructionDoctorTests { try fixture.write( String(repeating: "y", count: 20_000), to: nested.appendingPathComponent("AGENTS.md")) try fixture.write("", to: nested.appendingPathComponent("AGENTS.override.md")) + try fixture.write( + String(repeating: "z", count: 30_000), + to: fixture.home.appendingPathComponent(".codex/AGENTS.md")) try fixture.write( String(repeating: "ignored", count: 20_000), to: fixture.root.appendingPathComponent("AGENTS.md")) var runtime = fixture.environment runtime.projectDirectory = nested + #expect( + try !InstructionOperations.doctor(environment: runtime).diagnostics.contains { + $0.kind == .codexSize + }) + try fixture.write( + "project_doc_max_bytes = 16384\n", + to: fixture.home.appendingPathComponent(".codex/config.toml")) let report = try InstructionOperations.doctor(environment: runtime) let size = try #require(report.diagnostics.first { $0.kind == .codexSize }) - #expect(size.message.contains("40002 bytes")) + #expect(size.message.contains("20000 bytes")) + #expect(!size.message.contains(fixture.home.appendingPathComponent(".codex").path)) #expect(!size.message.contains(fixture.root.appendingPathComponent("AGENTS.md").path)) - try fixture.write( - "project_doc_max_bytes = 65536\n", - to: fixture.home.appendingPathComponent(".codex/config.toml")) + } + + @Test func codexOverrideHidesManagedFilesEvenWhenEmptyInProjects() throws { + let fixture = try InstructionFixture() + try fixture.section("rules") + try fixture.commit() + try fixture.add(agents: [.codex]) + try fixture.add(scope: .user, agents: [.codex]) + try fixture.write("", to: fixture.project.appendingPathComponent("AGENTS.override.md")) + try fixture.write(" \n", to: fixture.home.appendingPathComponent(".codex/AGENTS.override.md")) #expect( - try !InstructionOperations.doctor(environment: runtime).diagnostics.contains { - $0.kind == .codexSize + try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { + $0.kind == .codexOverride }) + #expect( + try !InstructionOperations.doctor(scope: .user, environment: fixture.environment) + .diagnostics.contains { $0.kind == .codexOverride }) + try fixture.write( + "Override\n", to: fixture.home.appendingPathComponent(".codex/AGENTS.override.md")) + #expect( + try InstructionOperations.doctor(scope: .user, environment: fixture.environment) + .diagnostics.contains { $0.kind == .codexOverride }) } - @Test func malformedMarkersAndLostLockProduceDiagnostics() throws { + @Test func editedTargetAndLostLockProduceDiagnostics() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() @@ -229,7 +255,7 @@ struct InstructionDoctorTests { to: fixture.project.appendingPathComponent("AGENTS.md")) #expect( try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { - $0.kind == .invalidTarget + $0.kind == .drift }) try FileManager.default.removeItem(at: fixture.store().resolvedURL) #expect( diff --git a/Tests/AgentsInstructionsTests/GenerationTests.swift b/Tests/AgentsInstructionsTests/GenerationTests.swift new file mode 100644 index 0000000..55949df --- /dev/null +++ b/Tests/AgentsInstructionsTests/GenerationTests.swift @@ -0,0 +1,85 @@ +import AgentsInstructions +import Foundation +import Testing + +@Suite("Generated targets") +struct GenerationTests { + @Test func rendersNoticeThenSectionsInOrder() throws { + let one = try unit("---\ndescription: d\n---\n# One\nFirst.\n", id: "a:one") + let two = try unit("---\ndescription: d\n---\n## Two\nSecond.\n", id: "a:two") + let text = try Instructions.render([two, one]) + #expect(text == generated(["## Two\nSecond.", "# One\nFirst."])) + #expect(Instructions.isGenerated(Data(text.utf8))) + #expect(Instructions.isGenerated(Data([0xEF, 0xBB, 0xBF]) + Data(text.utf8))) + } + + @Test func rejectsEqualHeadingsOnlyAtTheSameLevel() throws { + let first = try unit("---\ndescription: d\n---\n# Rules\nA.\n", id: "a:one") + let same = try unit("---\ndescription: d\n---\n# Rules \nB.\n", id: "a:two") + let deeper = try unit("---\ndescription: d\n---\n## Rules\nC.\n", id: "a:three") + #expect( + throws: InstructionError.duplicateHeading(heading: "Rules", sectionIDs: ["a:one", "a:two"]) + ) { + try Instructions.render([first, same]) + } + #expect(throws: Never.self) { try Instructions.render([first, deeper]) } + #expect(throws: InstructionError.invalidAssembly) { try Instructions.render([]) } + } + + @Test(arguments: [ + "Owner text.\n", "", "\n", + "\n" + Instructions.notice + "\n", + ]) + func otherFilesAreNotGenerated(_ text: String) { + #expect(!Instructions.isGenerated(Data(text.utf8))) + } + + @Test func findsLocalLinksOutsideCode() { + let text = """ + [Guide](docs/guide.md#start) and ![Logo](assets/logo%20mark.png?raw=1) + [Web](https://example.com/a.md), [Anchor](#rules), [File](file:///etc/hosts) + [Mail](mailto:team@example.com) `[Code](code.md)` raw + + [unused]: + + ``` + [Fenced](fenced.md) + [defined]: fenced.md + ``` + """ + let links = Instructions.localLinks(in: text) + #expect(links.map(\.kind) == [.link, .image, .link, .html, .definition]) + #expect( + links.compactMap(\.path) == [ + "docs/guide.md", "assets/logo mark.png", "/etc/hosts", "notes/used.md", + ]) + } + + @Test func chatGPTPromptsKeepScopesAndAppendCustomBytes() throws { + let scoped = try unit( + "---\ndescription: d\npaths: [\"**/*.swift\"]\n---\n# Swift\nUse care.\n") + let custom = Data("Custom\r\n".utf8) + let rendered = try Instructions.renderChatGPT(sections: [scoped], customContent: custom) + #expect( + rendered + == Data( + "# Swift\n\nApplies when working on files matching `**/*.swift`.\n\nUse care.\n\n".utf8) + + custom) + #expect(throws: InstructionError.emptyPrompt) { + try Instructions.renderChatGPT(sections: []) + } + #expect(throws: InstructionError.invalidUTF8) { + try Instructions.renderChatGPT(sections: [scoped], customContent: Data([0xFF])) + } + } + + @Test func claudeImportDriftUsesTheManagedBlock() throws { + let block = ClaudeForwarding.renderBlock(for: .root) + let hash = "sha256:" + String(repeating: "0", count: 64) + #expect( + try Instructions.detectDrift(in: Data("Custom.\n".utf8), lockedBlockHash: hash) == .missing) + #expect( + try Instructions.detectDrift(in: Data(("Custom.\n\n" + block).utf8), lockedBlockHash: hash) + == .drifted) + } +} diff --git a/Tests/AgentsInstructionsTests/LifecycleFixture.swift b/Tests/AgentsInstructionsTests/LifecycleFixture.swift index 9645cde..a5e8720 100644 --- a/Tests/AgentsInstructionsTests/LifecycleFixture.swift +++ b/Tests/AgentsInstructionsTests/LifecycleFixture.swift @@ -45,10 +45,33 @@ final class InstructionFixture { try Data(text.utf8).write(to: file) } - func section(_ name: String, body: String = "Original", container: String = "instructions") throws + func section( + _ name: String, body: String = "Original", container: String = "instructions", + heading: String? = nil, paths: [String] = [] + ) throws { + try write( + unitText(name, body: body, heading: heading, paths: paths), + to: repo.appendingPathComponent(container + "/" + name + ".md")) + } + + /// Writes one of the project's own instructions files in `.agent/instructions/`. + func own(_ name: String, body: String = "Original", heading: String? = nil, paths: [String] = []) + throws { try write( - "# \(name)\n\n\(body)\n", to: repo.appendingPathComponent(container + "/" + name + ".md")) + unitText(name, body: body, heading: heading, paths: paths), + to: project.appendingPathComponent(".agent/instructions/" + name + ".md")) + } + + @discardableResult + func addOwn( + names: [String], agents: [AgentID]? = nil, replace: Bool = false, + environment: RuntimeEnvironment? = nil + ) throws -> InstructionAddOutcome { + try InstructionOperations.add( + InstructionAddOptions( + source: ".", names: names, replace: replace, agents: agents, + environment: environment ?? self.environment)) } @discardableResult @@ -109,6 +132,23 @@ final class InstructionFixture { } } +/// An instructions file: front matter, then the body under `heading`, by default `# `. +func unitText( + _ name: String, body: String = "Original", heading: String? = nil, paths: [String] = [], + description: String? = nil +) -> String { + var front = "---\ndescription: \(description ?? "Instructions for \(name).")\n" + if !paths.isEmpty { + front += "paths: [" + paths.map { "\"\($0)\"" }.joined(separator: ", ") + "]\n" + } + return front + "---\n" + (heading ?? "# \(name)") + "\n\n" + body + "\n" +} + +/// A generated target: the notice, then each section body, one blank line apart. +func generated(_ bodies: [String]) -> String { + ([Instructions.notice] + bodies).joined(separator: "\n\n") + "\n" +} + private func removeTemporaryDirectory(_ directory: URL) { do { try FileManager.default.removeItem(at: directory) diff --git a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift index 261843e..cfa1e57 100644 --- a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift @@ -46,21 +46,20 @@ struct InstructionLifecycleSafetyTests { #expect(try Data(contentsOf: fixture.store().resolvedURL) == lock) } - @Test func installUsesLockedOffsetAndRejectsCustomConflicts() throws { + @Test func installRestoresTheLockedRenderingOverEdits() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() - try fixture.write("# Project\n", to: fixture.project.appendingPathComponent("AGENTS.md")) try fixture.add() + let locked = try fixture.bytes() try fixture.write("", to: fixture.project.appendingPathComponent("AGENTS.md")) _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) - #expect(try fixture.text().contains("## rules")) + #expect(try fixture.bytes() == locked) try fixture.write( - "## rules\n\nConflicting.\n", to: fixture.project.appendingPathComponent("AGENTS.md")) - #expect(throws: (any Error).self) { - try InstructionOperations.installResolvedReport(environment: fixture.environment) - } - #expect(try fixture.text() == "## rules\n\nConflicting.\n") + "## rules\n\nEdited.\n", to: fixture.project.appendingPathComponent("AGENTS.md")) + let report = try InstructionOperations.installResolvedReport(environment: fixture.environment) + #expect(report.targets.first?.drift == .drifted) + #expect(try fixture.bytes() == locked) } @Test func addPreservesOtherPinsAndSharedSkillState() throws { @@ -133,17 +132,16 @@ struct InstructionLifecycleSafetyTests { #expect(!FileManager.default.fileExists(atPath: fixture.store().resolvedURL.path)) } - @Test func removalPreservesCustomContentAndCleansForwarder() throws { + @Test func removalKeepsAnEditedTargetAndCleansForwarder() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() try fixture.write("Claude custom.\n", to: fixture.project.appendingPathComponent("CLAUDE.md")) try fixture.add() - try fixture.write( - try fixture.text() + "\n# Custom\n\nKeep.\n", - to: fixture.project.appendingPathComponent("AGENTS.md")) + let edited = try fixture.text() + "\n# Custom\n\nKeep.\n" + try fixture.write(edited, to: fixture.project.appendingPathComponent("AGENTS.md")) try InstructionOperations.remove(names: ["rules"], environment: fixture.environment) - #expect(try fixture.text() == "# Custom\n\nKeep.\n") + #expect(try fixture.text() == edited) #expect(try fixture.text("CLAUDE.md") == "Claude custom.\n") } diff --git a/Tests/AgentsInstructionsTests/LifecycleTests.swift b/Tests/AgentsInstructionsTests/LifecycleTests.swift index 7be2ced..5ef2025 100644 --- a/Tests/AgentsInstructionsTests/LifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleTests.swift @@ -111,26 +111,20 @@ struct InstructionLifecycleTests { #expect(!report.hasChanges) } - @Test func orderedBlocksPreserveCustomBytesAndRestoreLockedContent() throws { + @Test func generatedTargetRestoresLockedContentAndReplacesDrift() throws { let fixture = try InstructionFixture() try fixture.section("one") try fixture.section("two") try fixture.commit() - try fixture.write( - "# Project\n\nOwner text.\n\n## Custom\n\nKeep this.\n", - to: fixture.project.appendingPathComponent("AGENTS.md")) try fixture.add(names: ["two", "one"]) let first = try fixture.bytes() - let text = try fixture.text() - #expect(text.range(of: "## two")!.lowerBound < text.range(of: "## one")!.lowerBound) - #expect(text.hasPrefix("# Project\n\nOwner text.\n\n")) - #expect(text.hasSuffix("\n\n## Custom\n\nKeep this.\n")) + #expect(try fixture.text() == generated(["# two\n\nOriginal", "# one\n\nOriginal"])) let lock = try Data(contentsOf: fixture.store().resolvedURL) _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) #expect(try fixture.bytes() == first) #expect(try Data(contentsOf: fixture.store().resolvedURL) == lock) try fixture.write( - text.replacingOccurrences(of: "Original", with: "Drift"), + try fixture.text().replacingOccurrences(of: "Original", with: "Drift"), to: fixture.project.appendingPathComponent("AGENTS.md")) #expect( try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { @@ -139,13 +133,12 @@ struct InstructionLifecycleTests { try fixture.section("one", body: "Upstream") try fixture.commit() let preview = try InstructionOperations.updateInstalled(environment: fixture.environment) - #expect(preview.targets[0].assembly.blockDifference?.contains("Drift") == true) + #expect(preview.targets[0].drift == .drifted) + #expect(!preview.targets[0].foreign) _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) - #expect(try fixture.text().contains("Upstream")) + #expect(try fixture.text() == generated(["# two\n\nOriginal", "# one\n\nUpstream"])) let applied = try fixture.bytes() - try fixture.write( - try fixture.text().replacingOccurrences(of: "Upstream", with: "Drift"), - to: fixture.project.appendingPathComponent("AGENTS.md")) + try fixture.write("Drift\n", to: fixture.project.appendingPathComponent("AGENTS.md")) _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) #expect(try fixture.bytes() == applied) } @@ -277,62 +270,65 @@ struct InstructionLifecycleTests { #expect(try fixture.bytes() == bytes) #expect(try fixture.store().loadResolved().instructions.targets["AGENTS.md"]?.created == false) try InstructionOperations.remove(names: ["rules"], environment: fixture.environment) - #expect(try fixture.bytes().isEmpty) + #expect( + !FileManager.default.fileExists( + atPath: fixture.project.appendingPathComponent("AGENTS.md").path)) } - @Test func conflictingCustomSectionStopsAddAndReplaceAdoptsIt() throws { + @Test func foreignFileStopsAddAndReplaceTakesItOver() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() try fixture.write( "# rules\n\nCustom rule.\n", to: fixture.project.appendingPathComponent("AGENTS.md")) let before = try fixture.bytes() - do { - try fixture.add() - Issue.record("Expected conflicting section") - } catch InstructionError.conflictingSections(let conflicts) { - #expect(conflicts[0].difference.contains("-Custom rule.")) - } + #expect(throws: InstructionError.unownedTargets(["AGENTS.md"])) { try fixture.add() } #expect(try fixture.bytes() == before) #expect(!FileManager.default.fileExists(atPath: fixture.store().declarationURL.path)) #expect(!FileManager.default.fileExists(atPath: fixture.store().resolvedURL.path)) - try fixture.add(replace: true) - #expect(try fixture.text().contains("Original")) - #expect(try fixture.store().loadResolved().instructions.targets["AGENTS.md"]?.created == false) + let outcome = try fixture.add(replace: true) + #expect(outcome.result?.targets.first?.foreign == true) + #expect(try fixture.text() == generated(["# rules\n\nOriginal"])) } - @Test(arguments: [false, true]) - func removingLastSectionDeletesOnlyOwnedEmptyFiles(_ existing: Bool) throws { + @Test func generatedFileWithoutLockIsOwnedAndIdenticalFileIsKept() throws { + let fixture = try InstructionFixture() + try fixture.section("rules") + try fixture.commit() + try fixture.write( + generated(["# old\n\nStale"]), to: fixture.project.appendingPathComponent("AGENTS.md")) + try fixture.add() + #expect(try fixture.text() == generated(["# rules\n\nOriginal"])) + } + + @Test func removingLastSectionDeletesOnlyTheLockedRendering() throws { let fixture = try InstructionFixture() try fixture.section("one") try fixture.section("two") try fixture.commit() - if existing { try fixture.write("", to: fixture.project.appendingPathComponent("AGENTS.md")) } try fixture.add() try InstructionOperations.remove(names: ["one"], environment: fixture.environment) - #expect(try fixture.text().contains("# two")) - #expect(try !fixture.text().contains("# one")) + #expect(try fixture.text() == generated(["# two\n\nOriginal"])) + try fixture.write("Edited\n", to: fixture.project.appendingPathComponent("AGENTS.md")) try InstructionOperations.remove(names: ["two"], environment: fixture.environment) - #expect( - FileManager.default.fileExists( - atPath: fixture.project.appendingPathComponent("AGENTS.md").path) == existing) + #expect(try fixture.text() == "Edited\n") #expect(try fixture.store().loadResolved().instructions.targets.isEmpty) } - @Test func discoveryUsesOnlyDirectCommittedFilesAndSearchPath() throws { + @Test func discoveryReadsCommittedContainersRecursivelyFromSearchPath() throws { let fixture = try InstructionFixture() try fixture.section("one", container: "bundle/instructions") try fixture.section("two", container: "bundle/.agents/instructions") - try fixture.write( - "Invalid", to: fixture.repo.appendingPathComponent("bundle/instructions/nested/no.md")) + try fixture.section("three", container: "bundle/instructions/nested") try fixture.section("outside") try fixture.commit() try fixture.section("one", body: "Dirty", container: "bundle/instructions") let available = try InstructionOperations.list( source: SourceDeclaration(kind: .local, location: fixture.repo.path, path: "bundle"), environment: fixture.environment) - #expect(available.map(\.record.name) == ["one", "two"]) - try fixture.add(path: "bundle") + #expect(available.map(\.record.name) == ["nested/three", "one", "two"]) + #expect(available.map(\.section.description).first == "Instructions for three.") + try fixture.add(names: ["one"], path: "bundle") #expect(try !fixture.text().contains("Dirty")) #expect( try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { @@ -345,12 +341,41 @@ struct InstructionLifecycleTests { } } + @Test func discoveryRejectsInvalidNamesSymbolicLinksAndDuplicates() throws { + let fixture = try InstructionFixture() + try fixture.section("Upper") + try fixture.commit() + let source = SourceDeclaration(kind: .local, location: fixture.repo.path) + #expect(throws: (any Error).self) { + try InstructionOperations.list(source: source, environment: fixture.environment) + } + try FileManager.default.removeItem(at: fixture.repo.appendingPathComponent("instructions")) + try fixture.section("rules") + try fixture.section("rules", container: ".agents/instructions") + try fixture.git(["add", "-A"]) + try fixture.commit() + #expect(throws: (any Error).self) { + try InstructionOperations.list(source: source, environment: fixture.environment) + } + try FileManager.default.removeItem( + at: fixture.repo.appendingPathComponent(".agents/instructions")) + try FileManager.default.createSymbolicLink( + atPath: fixture.repo.appendingPathComponent("instructions/link.md").path, + withDestinationPath: "rules.md") + try fixture.git(["add", "-A"]) + try fixture.commit() + #expect(throws: (any Error).self) { + try InstructionOperations.list(source: source, environment: fixture.environment) + } + } + @Test func initializeCreatesValidatedSkeletonAndNeverOverwrites() throws { let fixture = try InstructionFixture() let file = try InstructionOperations.initializeInstructions( named: "new-rules", directory: fixture.repo.appendingPathComponent("instructions")) let section = try Instructions.validateSource(Data(contentsOf: file), id: "new-rules") #expect(section.heading == "new-rules") + #expect(section.level == 1) #expect(throws: (any Error).self) { try InstructionOperations.initializeInstructions( named: "new-rules", directory: file.deletingLastPathComponent()) diff --git a/Tests/AgentsInstructionsTests/ReferenceAndForwardingTests.swift b/Tests/AgentsInstructionsTests/ReferenceAndForwardingTests.swift deleted file mode 100644 index 99ca3e6..0000000 --- a/Tests/AgentsInstructionsTests/ReferenceAndForwardingTests.swift +++ /dev/null @@ -1,151 +0,0 @@ -import AgentsInstructions -import Foundation -import Testing - -@Suite("Reference definition ownership") -struct ReferenceDefinitionOwnershipTests { - @Test func replacementPreservesReferenceDefinitionBeforeSetextHeading() throws { - let target = "# Guide\n\n[ref]: /keep\nRules\n-----\nCustom.\n\n## Other\nSee [ref].\n" - let section = try source("# Rules\nManaged.\n") - let result = try Instructions.assemble( - Data(target.utf8), sections: [section], options: .init(replaceConflicts: true)) - #expect(result.conflicts.first?.existing == "Rules\n-----\nCustom.") - #expect( - result.bytes - == Data( - ("# Guide\n\n[ref]: /keep\n\n" + block("## Rules\nManaged.") + "\n## Other\nSee [ref].\n") - .utf8)) - #expect(try Instructions.assemble(result.bytes, sections: [section]).bytes == result.bytes) - #expect( - try Instructions.remove(from: result.bytes).bytes - == Data("# Guide\n\n[ref]: /keep\n## Other\nSee [ref].\n".utf8)) - } - - @Test(arguments: [ - "[ref]:\n /keep\n \"A title\n on two lines\"\n", - "[a\nlabel]: /first\n[ref]: \n 'A title'\n", - " [ref]:\n /keep\n (A title)\n", - ]) - func preservesMultilineReferenceDefinitions(_ definitions: String) throws { - let target = "# Guide\n\n" + definitions + "Rules\n-----\nCustom.\n\n## Other\nSee [ref].\n" - let result = try Instructions.assemble( - Data(target.utf8), sections: [source("# Rules\nManaged.\n")], - options: .init(replaceConflicts: true)) - #expect(result.conflicts.first?.existing == "Rules\n-----\nCustom.") - #expect( - result.bytes - == Data( - ("# Guide\n\n" + definitions + "\n" + block("## Rules\nManaged.") - + "\n## Other\nSee [ref].\n").utf8)) - } - - @Test func replacingParentSectionPreservesNestedHeadingDefinitions() throws { - let target = "# Rules\nCustom.\n\n[ref]: /keep\nDetail\n------\nMore.\n\n# Other\nSee [ref].\n" - let result = try Instructions.assemble( - Data(target.utf8), sections: [source("# Rules\nManaged.\n")], - options: .init(headingOffset: 0, replaceConflicts: true)) - #expect( - result.bytes - == Data((block("# Rules\nManaged.") + "\n[ref]: /keep\n# Other\nSee [ref].\n").utf8)) - #expect(result.conflicts.first?.existing == "# Rules\nCustom.\n\nDetail\n------\nMore.") - } - - @Test func precedingSelectedSectionDoesNotOwnDefinitions() throws { - let target = - "# Guide\n\n## First\nCustom.\n\n[ref]: /keep\nRules\n-----\nCustom.\n\n## Other\nSee [ref].\n" - let sections = try [ - source("# First\nOne\n", id: "first"), source("# Rules\nTwo\n", id: "rules"), - ] - let result = try Instructions.assemble( - Data(target.utf8), sections: sections, options: .init(replaceConflicts: true)) - #expect( - result.bytes - == Data( - ("# Guide\n\n" + block("## First\nOne\n\n## Rules\nTwo") - + "\n[ref]: /keep\n## Other\nSee [ref].\n").utf8)) - #expect(result.conflicts.map(\.existing) == ["## First\nCustom.", "Rules\n-----\nCustom."]) - } - - @Test func invalidReferenceLikeTextRemainsHeadingContent() throws { - let target = "[ref]: invalid destination\nRules\n=====\nBody\n" - let section = try source("# [ref]: invalid destination Rules\nManaged.\n") - let result = try Instructions.assemble( - Data(target.utf8), sections: [section], options: .init(replaceConflicts: true)) - #expect(result.conflicts.first?.existing == String(target.dropLast())) - #expect(!result.hasCustomContent) - } - - @Test func ambiguousMatchesReportPhysicalContentLines() throws { - let target = "# Guide\n\n[one]: /keep\nRules\n-----\nA\n\n[two]:\n /keep\nRules\n-----\nB\n" - #expect(throws: InstructionError.ambiguousMatch(sectionID: "rules:care", lines: [4, 10])) { - try Instructions.assemble(Data(target.utf8), sections: [source()]) - } - } - - @Test func largeSetextSelectionPreservesEveryDefinition() throws { - let count = 2_000 - let definitions = (0.. @AGENTS.md", "- @AGENTS.md", - "@**folder**/../AGENTS.md", "@AGENTS.md/backup", "@AGENTS.md\n===\n", - "**start\n@AGENTS.md\nend**\n", "`start\n@AGENTS.md\nend`\n", - "\n", "[ref]: /url \"title\n@AGENTS.md\nend\"\n", - ]) - func requiresManagedImportForMentionsAndExamples(_ content: String) throws { - let bytes = Data(content.utf8) - #expect(try !ClaudeForwarding.containsImport(in: bytes, at: .root)) - #expect( - try ClaudeForwarding.classify([.init(path: .root, bytes: bytes)]) == .needsImport(.root)) - } - - @Test(arguments: [ - "@AGENTS.md", " @AGENTS.md \t", "@./AGENTS.md", "@rules/../AGENTS.md\n", - "@Design\\ Docs/../AGENTS.md", "P with `code`\n@AGENTS.md\n", - "[ref]: /url\n@AGENTS.md\n", "P\r\n@AGENTS.md\r", "P\n\t@AGENTS.md\n", - "agents-forwarding-line-0\n@AGENTS.md\n", - ]) - func recognizesStandaloneImportLines(_ content: String) throws { - #expect(try ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) - } - - @Test(arguments: ["@../AGENTS.md", " @.././AGENTS.md \t", "@../Design\\ Docs/../AGENTS.md"]) - func recognizesStandaloneDirectoryRelativeImports(_ content: String) throws { - #expect(try ClaudeForwarding.containsImport(in: Data(content.utf8), at: .directory)) - } - - @Test func standaloneCodeLineCannotBorrowProseImport() throws { - let content = "See @AGENTS.md\n\n```\n@AGENTS.md\n```\n" - #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) - } - - @Test func managedBlockForwardsAlongsideProseMentions() throws { - let content = "**@AGENTS.md**/backup\n\n" + ClaudeForwarding.renderBlock(for: .root) - #expect(try ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) - } -} diff --git a/Tests/AgentsInstructionsTests/RenderingTests.swift b/Tests/AgentsInstructionsTests/RenderingTests.swift deleted file mode 100644 index b359b93..0000000 --- a/Tests/AgentsInstructionsTests/RenderingTests.swift +++ /dev/null @@ -1,184 +0,0 @@ -import AgentsInstructions -import Foundation -import Testing - -@Suite("Instruction rendering and drift") -struct InstructionRenderingTests { - @Test func detectsCleanDriftAndMissingBlock() throws { - let result = try Instructions.assemble(Data(), sections: [source()]) - let hash = try #require(result.blockHash) - #expect(try Instructions.detectDrift(in: result.bytes, lockedBlockHash: hash) == .clean) - let changed = Data(text(result).replacingOccurrences(of: "Use care.", with: "Changed.").utf8) - let drift = try Instructions.detectDrift( - in: changed, lockedBlockHash: hash, lockedBlock: result.block) - guard case .drifted(let actual, let difference) = drift else { - Issue.record("Expected block drift") - return - } - #expect(actual == block("# Rules\nChanged.")) - #expect(difference?.contains("-Use care.\n+Changed.") == true) - #expect( - try Instructions.detectDrift(in: Data("Custom\n".utf8), lockedBlockHash: hash) - == .missingBlock) - } - - @Test func hashOnlyDriftDoesNotInventBaselineText() throws { - let result = try Instructions.assemble(Data(), sections: [source()]) - let drift = try Instructions.detectDrift(in: result.bytes, lockedBlockHash: "sha256:different") - #expect(drift == .drifted(actualBlock: try #require(result.block), difference: nil)) - } - - @Test func driftIgnoresCustomChangesAndNormalizesBlockLineEndings() throws { - let result = try Instructions.assemble(Data(), sections: [source()]) - let target = - "Custom\r\n\r\n" + text(result).replacingOccurrences(of: "\n", with: "\r\n") - + "\r\nChanged custom\r\n" - #expect( - try Instructions.detectDrift( - in: Data(target.utf8), lockedBlockHash: #require(result.blockHash)) == .clean) - } - - @Test func rejectsIncorrectLockedBaseline() throws { - let result = try Instructions.assemble(Data(), sections: [source()]) - #expect(throws: InstructionError.invalidLockedBlock) { - try Instructions.detectDrift( - in: result.bytes, lockedBlockHash: #require(result.blockHash), lockedBlock: block("# Wrong") - ) - } - } - - @Test func driftRejectsMalformedTargetMarkers() { - #expect(throws: InstructionError.unpairedMarker(line: 1)) { - try Instructions.detectDrift(in: Data(beginMarker.utf8), lockedBlockHash: "any") - } - } - - @Test func blockHashIncludesMarkersAndSourceHashIncludesOriginalBytes() throws { - let first = try Instructions.assemble(Data(), sections: [source()]) - let shifted = try Instructions.assemble( - Data(), sections: [source()], options: .init(headingOffset: 1)) - #expect(first.blockHash != shifted.blockHash) - #expect(try first.blockHash != source().hash) - let paddedContent = text(first).replacingOccurrences(of: "Use care.", with: "Use care. ") - guard - case .drifted = try Instructions.detectDrift( - in: Data(paddedContent.utf8), lockedBlockHash: #require(first.blockHash)) - else { - Issue.record("Content whitespace is block drift") - return - } - } - - @Test func restoresDriftedBlockWithLockedOffset() throws { - let original = try Instructions.assemble( - Data(), sections: [source()], options: .init(headingOffset: 1)) - let changed = Data(text(original).replacingOccurrences(of: "Use care.", with: "Drift").utf8) - let restored = try Instructions.assemble( - changed, sections: [source()], options: .init(headingOffset: 1)) - #expect(restored.bytes == original.bytes) - #expect(restored.blockDifference?.contains("-Drift") == true) - } - - @Test func chatGPTKeepsSourceHeadingsAndOrder() throws { - let rendered = try Instructions.renderChatGPT(sections: [ - source("# One\n\n## Child\nA\n"), source("# Two\nB\n", id: "two"), - ]) - #expect(String(decoding: rendered, as: UTF8.self) == "# One\n\n## Child\nA\n\n# Two\nB\n") - } - - @Test func chatGPTAppendsCustomBytes() throws { - let rendered = try Instructions.renderChatGPT( - sections: [source()], customContent: Data("Custom\r\nExact ".utf8)) - #expect(String(decoding: rendered, as: UTF8.self) == "# Rules\nUse care.\n\nCustom\r\nExact ") - #expect( - try Instructions.renderChatGPT(sections: [source()], customContent: Data()) - == Instructions.renderChatGPT(sections: [source()])) - } - - @Test func chatGPTRejectsEmptySelectionAndInvalidCustomEncoding() { - #expect(throws: InstructionError.emptyPrompt) { - try Instructions.renderChatGPT(sections: [], customContent: Data("Only custom".utf8)) - } - #expect(throws: InstructionError.invalidUTF8) { - try Instructions.renderChatGPT(sections: [source()], customContent: Data([0xFF])) - } - } - - @Test func chatGPTRejectsDuplicateHeadings() { - #expect(throws: InstructionError.self) { - try Instructions.renderChatGPT(sections: [source(), source(id: "different")]) - } - } - @Test func missingFinalNewlineIsBlockDrift() throws { - let result = try Instructions.assemble(Data(), sections: [source()]) - let changed = Data(text(result).dropLast().utf8) - let drift = try Instructions.detectDrift( - in: changed, lockedBlockHash: #require(result.blockHash), lockedBlock: result.block) - guard case .drifted(_, let difference) = drift else { - Issue.record("Expected final newline drift") - return - } - #expect(difference?.contains("No newline at end of proposed text") == true) - } - -} - -@Suite("Claude forwarding") -struct ClaudeForwardingTests { - @Test(arguments: ClaudeInstructionPath.allCases) - func rendersRelativeImportBlock(_ path: ClaudeInstructionPath) throws { - let expected = path == .directory ? "@../AGENTS.md" : "@AGENTS.md" - let rendered = ClaudeForwarding.renderBlock(for: path) - #expect(rendered == block(expected)) - #expect(try ClaudeForwarding.containsImport(in: Data(rendered.utf8), at: path)) - } - - @Test(arguments: ["@AGENTS.md", "@./AGENTS.md", "@rules/../AGENTS.md"]) - func recognizesEquivalentImport(_ line: String) throws { - #expect( - try ClaudeForwarding.containsImport(in: Data(("# Guide\n\n" + line + "\n").utf8), at: .root)) - } - - @Test(arguments: ["@AGENTS.md", "@../../AGENTS.md", "@\"../AGENTS.md\"", "@../AGENTS.md/"]) - func rejectsWrongDirectoryImport(_ line: String) throws { - #expect(try !ClaudeForwarding.containsImport(in: Data(line.utf8), at: .directory)) - } - - @Test func ignoresImportsInsideCode() throws { - let target = "```\n@AGENTS.md\n```\n\n @AGENTS.md\n" - #expect(try !ClaudeForwarding.containsImport(in: Data(target.utf8), at: .root)) - } - - @Test func rootSymlinkAlreadyForwards() throws { - let files = [ClaudeInstructionFile(path: .root, isSymbolicLinkToAgents: true)] - #expect(try ClaudeForwarding.classify(files) == .forwarding(.root)) - #expect(try ClaudeForwarding.classify([.init(path: .root)]) == .needsImport(.root)) - } - - @Test func choosesFirstExistingClaudeFile() throws { - #expect( - try ClaudeForwarding.classify([ - .init(path: .local), .init(path: .directory), .init(path: .root), - ]) == .needsImport(.root)) - #expect( - try ClaudeForwarding.classify([.init(path: .local), .init(path: .directory)]) - == .needsImport(.directory)) - #expect(try ClaudeForwarding.classify([.init(path: .local)]) == .needsImport(.local)) - #expect(try ClaudeForwarding.classify([]) == .automatic) - } - - @Test func existingImportInAnotherProjectFileForwards() throws { - let files = [ - ClaudeInstructionFile(path: .root), - ClaudeInstructionFile(path: .directory, bytes: Data("@../AGENTS.md\n".utf8)), - ] - #expect(try ClaudeForwarding.classify(files) == .forwarding(.directory)) - } - - @Test func rejectsMalformedForwardingMarkers() { - #expect(throws: InstructionError.self) { - try ClaudeForwarding.containsImport( - in: Data((beginMarker + "\n@AGENTS.md\n").utf8), at: .root) - } - } -} diff --git a/Tests/AgentsInstructionsTests/SemanticTextTests.swift b/Tests/AgentsInstructionsTests/SemanticTextTests.swift deleted file mode 100644 index c2bf692..0000000 --- a/Tests/AgentsInstructionsTests/SemanticTextTests.swift +++ /dev/null @@ -1,192 +0,0 @@ -import AgentsInstructions -import Foundation -import Testing - -@Suite("Instruction semantic text and physical lines") -struct InstructionSemanticTextTests { - @Test func referenceDefinitionDoesNotChangeHeadingIdentity() throws { - let target = "[ref]: /url\nRules\n=====\nKeep this custom content.\n" - let section = try source("# [ref]\nManaged.\n") - let result = try Instructions.assemble( - Data(target.utf8), sections: [section], options: .init(replaceConflicts: true)) - #expect(result.headingOffset == 1) - #expect(result.conflicts.isEmpty) - #expect(result.hasCustomContent) - #expect(result.bytes == Data((target + "\n" + block("## [ref]\nManaged.")).utf8)) - #expect(try Instructions.assemble(result.bytes, sections: [section]).bytes == result.bytes) - } - - @Test func referenceDefinitionKeepsSetextUnderlineBeforeNextHeading() throws { - let target = "[ref]: /url\nRules\n=====\n## Custom\nKeep.\n" - let result = try Instructions.assemble(Data(target.utf8), sections: [source("# Other\nBody\n")]) - #expect( - result.bytes - == Data( - ("[ref]: /url\nRules\n=====\n\n" + block("## Other\nBody") + "\n## Custom\nKeep.\n").utf8) - ) - } - - @Test func tabIndentedSetextContinuationUsesSemanticUnicodeText() throws { - let target = "Guide\n\t规则\n===\nBody\n" - let section = try source("# Guide 规则\nBody\n") - let result = try Instructions.assemble( - Data(target.utf8), sections: [section], options: .init(replaceConflicts: true)) - #expect(result.headingOffset == 0) - #expect(result.conflicts.count == 1) - #expect(result.conflicts.first?.existing == String(target.dropLast())) - #expect(result.bytes == Data(block("# Guide 规则\nBody").utf8)) - #expect(!result.hasCustomContent) - } - - @Test(arguments: ["#Rules\n=====\n", "##Rules\n=====\n", "# Rules\n\n> ##Detail\n> ---\n"]) - func rejectsSetextWithHashPrefix(_ content: String) { - #expect(throws: InstructionError.self) { try source(content) } - } - - @Test(arguments: [ - ("#\tRules\n", "##\tRules"), ("#\n", "##"), - ("# Rules\n\n-\t## Detail\n", "## Rules\n\n-\t### Detail"), - ("# Rules\n\n> 2. ## Detail\n", "## Rules\n\n> 2. ### Detail"), - ("# Rules\n\n- item\n > ## Detail\n", "## Rules\n\n- item\n > ### Detail"), - ]) - func shiftsVerifiedATXOpenings(_ content: String, _ shifted: String) throws { - let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [source(content)]) - #expect(result.block == block(shifted)) - } - - @Test func headingIdentityUsesSemanticInlineText() throws { - let section = try source("# **Rules** & [care](https://example.com) `now`\nBody\n") - #expect(section.heading == "Rules & care `now`") - let target = "# Rules & care `now`\nCustom\n" - let result = try Instructions.assemble( - Data(target.utf8), sections: [section], options: .init(replaceConflicts: true)) - #expect(result.headingOffset == 0) - #expect(result.conflicts.first?.existing == "# Rules & care `now`\nCustom") - #expect(result.block == block("# **Rules** & [care](https://example.com) `now`\nBody")) - } - - @Test func semanticHeadingsRejectDuplicateSelections() throws { - let sections = try [source("# *Rules*\nA\n", id: "one"), source("# Rules\nB\n", id: "two")] - #expect( - throws: InstructionError.duplicateHeading(heading: "Rules", sectionIDs: ["one", "two"]) - ) { - try Instructions.assemble(Data(), sections: sections) - } - } - - @Test func semanticHeadingsRejectAmbiguousMatches() throws { - let target = "# *Rules*\nA\n\n# **Rules**\nB\n" - #expect(throws: InstructionError.ambiguousMatch(sectionID: "rules:care", lines: [1, 4])) { - try Instructions.assemble(Data(target.utf8), sections: [source()]) - } - } - - @Test(arguments: ["=", " === \t", " =====", "===\t"]) - func verifiesPhysicalSetextUnderline(_ underline: String) throws { - let target = "Guide\n" + underline + "\n## Custom\nKeep\n" - let result = try Instructions.assemble(Data(target.utf8), sections: [source()]) - #expect( - result.bytes - == Data( - ("Guide\n" + underline + "\n\n" + block("## Rules\nUse care.") + "\n## Custom\nKeep\n") - .utf8)) - } -} - -@Suite("Claude import examples") -struct ClaudeImportExampleTests { - @Test(arguments: [ - "[ref]: /url\n`@AGENTS.md`\n", - "P\n `@AGENTS.md`\n", - "P\r\n `@AGENTS.md`\r", - "P\n\t\t\t\t\t\t\t\t\t\t\t\t`@AGENTS.md`\n", - "P\r\n\t\t\t\t\t\t\t\t\t\t\t\t`@AGENTS.md`\r", - ]) - func codeSpanNeverForwards(_ content: String) throws { - let bytes = Data(content.utf8) - #expect(try !ClaudeForwarding.containsImport(in: bytes, at: .root)) - #expect( - try ClaudeForwarding.classify([.init(path: .root, bytes: bytes)]) == .needsImport(.root)) - } - - @Test(arguments: [ - "[ref]: /url\n`example` and @AGENTS.md\n", - "P\n `example` and @AGENTS.md\n", - "P\r\n `example` and @AGENTS.md\r", - "**See @AGENTS.md**", "> Read @AGENTS.md", "- Read @AGENTS.md", - ]) - func proseTextNeedsManagedImport(_ content: String) throws { - #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) - #expect( - try ClaudeForwarding.classify([.init(path: .root, bytes: Data(content.utf8))]) - == .needsImport(.root)) - } - - @Test(arguments: [ - "", "\n@AGENTS.md\n\n", - "
\n@AGENTS.md\n
\n", "Read example", - "[ref]: /@AGENTS.md\nReference.\n", - ]) - func htmlAndReferenceDestinationsDoNotForward(_ content: String) throws { - #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root)) - } -} - -@Suite("Instruction UTF-8 byte order marks") -struct InstructionByteOrderMarkTests { - let bom = Data([0xEF, 0xBB, 0xBF]) - - @Test func preservesTargetByteOrderMarkAndTitle() throws { - let target = bom + Data("# Guide\n".utf8) - let section = try source("# Rules\nBody\n") - let result = try Instructions.assemble(target, sections: [section]) - #expect(result.headingOffset == 1) - #expect(result.bytes == bom + Data(("# Guide\n\n" + block("## Rules\nBody")).utf8)) - #expect(try Instructions.assemble(result.bytes, sections: [section]).bytes == result.bytes) - #expect(try Instructions.remove(from: result.bytes).bytes == target) - } - - @Test func preservesByteOrderMarkWhenPrependingBlock() throws { - let target = bom + Data("Custom\r\nExact \r".utf8) - let result = try Instructions.assemble(target, sections: [source()]) - #expect( - result.bytes == bom + Data((block("# Rules\nUse care.") + "\nCustom\r\nExact \r").utf8)) - #expect(result.hasCustomContent) - #expect(try Instructions.assemble(result.bytes, sections: [source()]).bytes == result.bytes) - } - - @Test func byteOrderMarkIsMetadataForRemovalAndDrift() throws { - let result = try Instructions.assemble(bom, sections: [source()]) - #expect(result.bytes == bom + Data(block("# Rules\nUse care.").utf8)) - #expect(!result.hasCustomContent) - #expect( - try Instructions.detectDrift(in: result.bytes, lockedBlockHash: #require(result.blockHash)) - == .clean) - let removed = try Instructions.remove(from: result.bytes) - #expect(removed.bytes == bom) - #expect(!removed.hasCustomContent) - let unchanged = try Instructions.remove(from: bom) - #expect(unchanged.bytes == bom) - #expect(!unchanged.hasCustomContent) - } - - @Test func sourceHashIncludesByteOrderMark() throws { - let plain = Data("# Rules\nBody\n".utf8) - let section = try Instructions.validateSource(bom + plain, id: "rules") - #expect(section.heading == "Rules") - #expect(try section.hash != Instructions.validateSource(plain, id: "rules").hash) - #expect(try Instructions.assemble(Data(), sections: [section]).block == block("# Rules\nBody")) - } - - @Test(arguments: ["# Guide\n", "Custom\r\nExact \r", ""]) - func chatGPTAppendsByteOrderMarkVerbatim(_ custom: String) throws { - let bytes = bom + Data(custom.utf8) - let result = try Instructions.renderChatGPT(sections: [source()], customContent: bytes) - #expect(result == Data("# Rules\nUse care.\n\n".utf8) + bytes) - } - - @Test func importParsingAcceptsByteOrderMark() throws { - #expect(try ClaudeForwarding.containsImport(in: bom + Data("@AGENTS.md\n".utf8), at: .root)) - #expect(try !ClaudeForwarding.containsImport(in: bom + Data("`@AGENTS.md`\n".utf8), at: .root)) - } -} diff --git a/Tests/AgentsInstructionsTests/SourceTests.swift b/Tests/AgentsInstructionsTests/SourceTests.swift deleted file mode 100644 index 6ac440a..0000000 --- a/Tests/AgentsInstructionsTests/SourceTests.swift +++ /dev/null @@ -1,130 +0,0 @@ -import AgentsInstructions -import Foundation -import Testing - -let beginMarker = - "" -let endMarker = "" - -func source(_ text: String = "# Rules\nUse care.\n", id: String = "rules:care") throws - -> InstructionSection -{ - try Instructions.validateSource(Data(text.utf8), id: id) -} - -func text(_ result: InstructionAssembly) -> String { - String(decoding: result.bytes, as: UTF8.self) -} - -func block(_ content: String) -> String { - beginMarker + "\n" + content + "\n" + endMarker + "\n" -} - -@Suite("Instruction sources") -struct InstructionSourceTests { - @Test func validatesATXSource() throws { - let section = try source("# Rules ###\nBody\n\n## Detail\nMore\n") - #expect(section.id == "rules:care") - #expect(section.heading == "Rules") - #expect(section.hash.hasPrefix("sha256:")) - #expect(section.hash.count == 71) - } - - @Test(arguments: [ - "", "Body\n", "Body\n# Rules\n", "## Detail\n# Rules\n", "# One\n# Two\n", - "Title\n===\n", "# Title\n\nDetail\n---\n", "#No space\n", "####### Too deep\n", - ]) - func rejectsInvalidSourceStructure(_ input: String) { - #expect(throws: InstructionError.self) { try source(input) } - } - - @Test(arguments: ["```", "~~~~ swift", " ```swift", " code", "\tcode"]) - func rejectsSourceEndingInCode(_ opening: String) { - #expect(throws: InstructionError.self) { try source("# Rules\n\n" + opening + "\n\n") } - } - - @Test(arguments: [ - "```\n# Hidden\n```", "~~~~\n# Hidden\n~~~\n~~~~", " # Hidden\n text", "\t# Hidden", - ]) - func ignoresCodeHeadings(_ code: String) throws { - let section = try source("# Rules\n\n" + code + "\n\nEnd.\n") - let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [section]) - #expect(text(result).contains("## Rules\n")) - #expect(text(result).contains(code)) - #expect(!text(result).contains("## Hidden")) - } - - @Test func ignoresMarkersInsideCode() throws { - let code = - "```html\n\(beginMarker)\n\(endMarker)\n```\n\n \(beginMarker)\n \(endMarker)\n\nEnd." - let section = try source("# Rules\n\n" + code) - let result = try Instructions.assemble(Data(), sections: [section]) - #expect(text(result).contains(code)) - #expect(try Instructions.assemble(result.bytes, sections: [section]).bytes == result.bytes) - } - - @Test func rejectsStructuralSourceMarker() { - #expect(throws: InstructionError.self) { try source("# Rules\n\(beginMarker)\n") } - } - - @Test func rejectsInvalidUTF8() { - #expect(throws: InstructionError.invalidUTF8) { - try Instructions.validateSource(Data([0xFF]), id: "invalid") - } - #expect(throws: InstructionError.invalidUTF8) { - try Instructions.assemble(Data([0xFF]), sections: [source()]) - } - } - - @Test func normalizesLineEndingsAndTrailingBlanks() throws { - let section = try source("# Rules\r\nBody\r\n\r\n \t\r\n") - let result = try Instructions.assemble(Data(), sections: [section]) - #expect(text(result) == block("# Rules\nBody")) - #expect(try section.hash != source("# Rules\nBody\n").hash) - } - - @Test func shiftsOnlyStructuralATXHeadings() throws { - let section = try source("# Rules\n\n## Detail ##\n\n```\n###### Example\n```\n") - let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [section]) - #expect(result.block == block("## Rules\n\n### Detail ##\n\n```\n###### Example\n```")) - } - - @Test func rejectsFalseFenceCloser() { - #expect(throws: InstructionError.self) { try source("# Rules\n```swift\nx\n``` trailing\n") } - #expect(throws: InstructionError.self) { try source("# Rules\n````\nx\n```\n") } - } - - @Test func backtickInfoCannotContainBackticks() throws { - let section = try source("# Rules\n\n```not`a`fence\n\n## Detail\n") - let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [section]) - #expect(text(result).contains("### Detail\n")) - } - @Test func ignoresFencedCodeOpenedInList() throws { - let code = "- ```\n # Hidden\n \(beginMarker)\n ```" - let section = try source("# Rules\n\n" + code + "\n\nEnd.\n") - let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [section]) - #expect(text(result).contains(code)) - } - - @Test func ignoresHeadingsAndMarkersInsideHTML() throws { - let html = "\n\n
\n# Hidden\n\(endMarker)\n
" - let section = try source("# Rules\n\n" + html + "\n\nEnd.\n") - let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [section]) - #expect(text(result).contains(html)) - } - - @Test func recognizesMultilineSetextTitle() throws { - let result = try Instructions.assemble( - Data("Project\nGuide\n====\n".utf8), sections: [source()]) - #expect(result.headingOffset == 1) - #expect(text(result).hasPrefix("Project\nGuide\n====\n\n")) - } - - @Test func thematicBreakDoesNotBecomeHeading() throws { - let section = try source("# Rules\n\n---\n\nBody\n") - #expect( - try Instructions.assemble(Data(), sections: [section]).block - == block("# Rules\n\n---\n\nBody")) - } - -} diff --git a/Tests/AgentsInstructionsTests/StructureTests.swift b/Tests/AgentsInstructionsTests/StructureTests.swift deleted file mode 100644 index 5059a97..0000000 --- a/Tests/AgentsInstructionsTests/StructureTests.swift +++ /dev/null @@ -1,231 +0,0 @@ -import AgentsInstructions -import Foundation -import Testing - -@Suite("Instruction Markdown structure") -struct InstructionStructureTests { - @Test func preservesCodeAcrossListContainerBoundary() throws { - let target = - "- item\n ```\n example\n```\n" + beginMarker - + "\n# Rules\nUse care.\n" + endMarker + "\n```\n" - let original = Data(target.utf8) - #expect(try Instructions.remove(from: original).bytes == original) - let result = try Instructions.assemble(original, sections: [source()]) - #expect(text(result) == block("# Rules\nUse care.") + "\n" + target) - } - - @Test func quotedLevelSixHeadingOverflowsUnderTitle() throws { - let section = try source("# Rules\n\n> ###### Deep\n") - #expect(throws: InstructionError.headingOverflow(sectionID: section.id, level: 6, offset: 1)) { - try Instructions.assemble(Data("# Guide\n".utf8), sections: [section]) - } - } - - @Test func shiftsHeadingsInsideListsAndQuotes() throws { - let content = "# Rules\n\n> ## Quoted *text*\n\n- ### Listed\n > #### Nested\n" - let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [source(content)]) - #expect( - result.block == block("## Rules\n\n> ### Quoted *text*\n\n- #### Listed\n > ##### Nested")) - } - - @Test(arguments: [ - "> # Other", "- # Other", "- item\n\n # Other", "> Title\n> =====", "- Title\n -----", - ]) - func rejectsH1AndSetextHeadingsInsideContainers(_ nested: String) { - #expect(throws: InstructionError.self) { try source("# Rules\n\n" + nested + "\n") } - } - - @Test(arguments: ["> # Rules\n", "- # Rules\n"]) - func requiresTopLevelSourceHeading(_ content: String) { - #expect(throws: InstructionError.self) { try source(content) } - } - - @Test func containerHeadingsAreNotTitlesOrMatches() throws { - let target = "> # Guide\n\n- # Rules\n Custom\n" - let result = try Instructions.assemble(Data(target.utf8), sections: [source()]) - #expect(result.headingOffset == 0) - #expect(result.adoptedSections.isEmpty) - #expect(result.conflicts.isEmpty) - #expect(text(result) == block("# Rules\nUse care.") + "\n" + target) - } - - @Test func containerHeadingsBelongToContainingSection() throws { - let content = "# Rules\nUse care.\n\n> ## Quoted\n> Content\n\n- ## Listed\n Content\n" - let result = try Instructions.assemble(Data(content.utf8), sections: [source(content)]) - #expect(result.adoptedSections == ["rules:care"]) - #expect(!result.hasCustomContent) - } - - @Test func recognizesThematicBreakAfterList() throws { - let content = "# Rules\n\n- item\n---\nBody\n" - let result = try Instructions.assemble(Data(), sections: [source(content)]) - #expect(result.block == block(String(content.dropLast()))) - } - - @Test func typeSevenHTMLDoesNotCreateTitle() throws { - let target = "\n# Guide\n" - let result = try Instructions.assemble(Data(target.utf8), sections: [source("# Rules\nBody\n")]) - #expect(result.headingOffset == 0) - #expect(text(result) == block("# Rules\nBody") + "\n" + target) - } - - @Test func typeOneHTMLAcceptsAnyDesignatedClosingTag() throws { - let content = "# Rules\n
\n\n## Detail\n"
-    let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [source(content)])
-    #expect(result.block == block("## Rules\n
\n\n### Detail"))
-  }
-
-  @Test(arguments: [
-    "", "", "", "", "
\n",
-    "> ", "- 
\n  ",
-  ])
-  func acceptsExplicitlyClosedHTMLAtEnd(_ html: String) throws {
-    let section = try source("# Rules\n\n" + html + "\n")
-    #expect(try Instructions.assemble(Data(), sections: [section]).block != nil)
-  }
-
-  @Test(arguments: [
-    "> ```\n> body", "- item\n  ```\n  body", "- > ~~~\n  > body", ">     indented",
-    "- item\n\n      indented",
-  ])
-  func rejectsSourceEndingInsideContainerCode(_ code: String) {
-    #expect(throws: InstructionError.self) { try source("# Rules\n\n" + code + "\n") }
-  }
-
-  @Test(arguments: [
-    "> ```\n> body\n> `````", "- item\n  ```\n  body\n  ```", "- > ~~~\n  > body\n  > ~~~~",
-  ])
-  func acceptsClosedContainerFences(_ code: String) throws {
-    let section = try source("# Rules\n\n" + code + "\n")
-    #expect(try Instructions.assemble(Data(), sections: [section]).block != nil)
-  }
-
-  @Test func onlyExactTopLevelSingleLineHTMLMarkersCount() throws {
-    let examples = [
-      "> \(beginMarker)\n> \(endMarker)\n",
-      "- \(beginMarker)\n\n- \(endMarker)\n",
-      "\n\(beginMarker)\n\(endMarker)\n\n",
-      " \(beginMarker)\n \(endMarker)\n",
-      "\(beginMarker) trailing\n\(endMarker) trailing\n",
-    ]
-    for target in examples {
-      let bytes = Data(target.utf8)
-      #expect(try Instructions.remove(from: bytes).bytes == bytes)
-    }
-    #expect(try Instructions.remove(from: Data(block("# Rules\nUse care.").utf8)).bytes.isEmpty)
-  }
-
-  @Test func setextRangeKeepsFollowingParagraphAndUnderlineTogether() throws {
-    let target = "Project\nGuide\n=====\nIntroduction\n\n## Custom\nKeep\n"
-    let result = try Instructions.assemble(Data(target.utf8), sections: [source()])
-    #expect(
-      text(result) == "Project\nGuide\n=====\nIntroduction\n\n" + block("## Rules\nUse care.")
-        + "\n## Custom\nKeep\n")
-  }
-
-  @Test(arguments: ["", " ", "  ", "   "])
-  func preservesHeadingIndentationAndInlineSyntax(_ indentation: String) throws {
-    let section = try source(indentation + "# Rüles *and* `code` ###\nBody\n")
-    #expect(section.heading == "Rüles and `code`")
-    let result = try Instructions.assemble(Data("# Guide\n".utf8), sections: [section])
-    #expect(result.block == block(indentation + "## Rüles *and* `code` ###\nBody"))
-  }
-
-  @Test func escapedOpeningHashIsNotHeading() throws {
-    let target = "\\# Guide\n"
-    let result = try Instructions.assemble(Data(target.utf8), sections: [source()])
-    #expect(result.headingOffset == 0)
-    #expect(text(result).hasSuffix(target))
-  }
-
-  @Test(arguments: [
-    "# Guide\r", "# Guide\r\nIntroduction\r", "# Guide\nIntroduction\r", "# Guide\rIntroduction\n",
-  ])
-  func lockedAssemblyIsIdempotentWithMixedLineEndings(_ target: String) throws {
-    let options = InstructionOptions(headingOffset: 1)
-    let first = try Instructions.assemble(Data(target.utf8), sections: [source()], options: options)
-    let second = try Instructions.assemble(first.bytes, sections: [source()], options: options)
-    #expect(second.bytes == first.bytes)
-    #expect(second.blockHash == first.blockHash)
-    if target == "# Guide\r" {
-      #expect(text(first) == "# Guide\r\n\n" + block("## Rules\nUse care."))
-    }
-  }
-
-  @Test func assembleRemoveAssemblePreservesLockedRendering() throws {
-    let options = InstructionOptions(headingOffset: 1)
-    let first = try Instructions.assemble(
-      Data("# Guide\n".utf8), sections: [source()], options: options)
-    let removed = try Instructions.remove(from: first.bytes)
-    let restored = try Instructions.assemble(removed.bytes, sections: [source()], options: options)
-    #expect(restored.bytes == first.bytes)
-  }
-
-  @Test(arguments: [2_000, 10_000])
-  func assemblesLargeMatchingSelection(_ count: Int) throws {
-    let contents = (0.. ```\n> @AGENTS.md\n> ```",
-    "@'AGENTS.md'", "\"@AGENTS.md\"", "contact@AGENTS.md",
-  ])
-  func ignoresCodeAndQuotedPaths(_ content: String) throws {
-    #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root))
-  }
-
-  @Test func inlineImportAfterCodeSpanNeedsManagedImport() throws {
-    let content = "Rüles\r\n`@wrong.md` then @AGENTS.md\r"
-    #expect(try !ClaudeForwarding.containsImport(in: Data(content.utf8), at: .root))
-  }
-
-  @Test func proseWithUnterminatedBacktickNeedsManagedImport() throws {
-    #expect(
-      try !ClaudeForwarding.containsImport(in: Data("See `literal and @AGENTS.md".utf8), at: .root))
-  }
-}
diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift
new file mode 100644
index 0000000..4e55a24
--- /dev/null
+++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift
@@ -0,0 +1,150 @@
+import AgentsCore
+import AgentsInstructions
+import Foundation
+import Testing
+
+@Suite("Own instructions and generated targets")
+struct TargetLifecycleTests {
+  @Test func ownInstructionsAreReadLiveAndRecordedByHash() throws {
+    let fixture = try InstructionFixture()
+    try fixture.section("shared")
+    try fixture.commit()
+    try fixture.own("guide", heading: "# Project Guide")
+    try fixture.own("review", heading: "## Code Review Rules")
+    try fixture.add(names: ["shared"])
+    try fixture.addOwn(names: ["guide", "review"])
+    #expect(
+      try fixture.store().loadDeclaration().instructions?.sections == [
+        "rules:shared", "guide", "review",
+      ])
+    #expect(
+      try fixture.text()
+        == generated([
+          "# shared\n\nOriginal", "# Project Guide\n\nOriginal", "## Code Review Rules\n\nOriginal",
+        ]))
+    let record = try #require(
+      try fixture.store().loadResolved().instructions.sections.first { $0.name == "guide" })
+    #expect(record.source == ".")
+    #expect(record.path == ".agent/instructions/guide.md")
+    #expect(record.revision == nil)
+    #expect(try InstructionOperations.listOwn(environment: fixture.environment).count == 2)
+
+    try fixture.own("guide", body: "Edited", heading: "# Project Guide")
+    #expect(
+      try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains {
+        $0.kind == .ownChanged
+      })
+    #expect(throws: (any Error).self) {
+      try InstructionOperations.installResolvedReport(environment: fixture.environment)
+    }
+    _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true)
+    #expect(try fixture.text().contains("# Project Guide\n\nEdited"))
+    #expect(
+      try !InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains {
+        $0.kind == .ownChanged
+      })
+  }
+
+  @Test func pathsPlaceSectionsInNestedTargets() throws {
+    let fixture = try InstructionFixture()
+    try FileManager.default.createDirectory(
+      at: fixture.project.appendingPathComponent("Sources/Render"),
+      withIntermediateDirectories: true)
+    try fixture.own("guide")
+    try fixture.own("render", paths: ["Sources/Render/**/*.swift"])
+    try fixture.own("swift", paths: ["**/*.swift"])
+    try fixture.addOwn(names: ["guide", "render", "swift"], agents: [.codex, .geminiCLI])
+    let scope = "Applies when working on files matching"
+    #expect(
+      try fixture.text()
+        == generated([
+          "# guide\n\nOriginal", "# swift\n\n\(scope) `**/*.swift`.\n\nOriginal",
+        ]))
+    let nested = generated(["# render\n\n\(scope) `Sources/Render/**/*.swift`.\n\nOriginal"])
+    #expect(try fixture.text("Sources/Render/AGENTS.md") == nested)
+    #expect(try fixture.text("Sources/Render/GEMINI.md") == nested)
+    #expect(
+      Set(try fixture.store().loadResolved().instructions.targets.keys) == [
+        "AGENTS.md", "GEMINI.md", "Sources/Render/AGENTS.md", "Sources/Render/GEMINI.md",
+      ])
+    try InstructionOperations.remove(names: ["render"], environment: fixture.environment)
+    #expect(
+      !FileManager.default.fileExists(
+        atPath: fixture.project.appendingPathComponent("Sources/Render/AGENTS.md").path))
+  }
+
+  @Test func nestedTargetsNeedExistingDirectoriesAndOwnedFiles() throws {
+    let fixture = try InstructionFixture()
+    try fixture.own("render", paths: ["Sources/Render/**"])
+    #expect(throws: (any Error).self) { try fixture.addOwn(names: ["render"]) }
+    try fixture.write(
+      "Hand written.\n", to: fixture.project.appendingPathComponent("Sources/Render/AGENTS.md"))
+    #expect(throws: InstructionError.unownedTargets(["Sources/Render/AGENTS.md"])) {
+      try fixture.addOwn(names: ["render"])
+    }
+    try fixture.addOwn(names: ["render"], replace: true)
+    #expect(try Instructions.isGenerated(fixture.bytes("Sources/Render/AGENTS.md")))
+  }
+
+  @Test func userTargetsScopeByTheLineAlone() throws {
+    let fixture = try InstructionFixture()
+    try fixture.section("swift", paths: ["**/*.swift"])
+    try fixture.commit()
+    try fixture.add(scope: .user, agents: [.codex])
+    #expect(
+      try String(
+        contentsOf: fixture.home.appendingPathComponent(".codex/AGENTS.md"), encoding: .utf8)
+        == generated([
+          "# swift\n\nApplies when working on files matching `**/*.swift`.\n\nOriginal"
+        ]))
+  }
+
+  @Test func linksMustResolveInTheCheckoutBeingWritten() throws {
+    let fixture = try InstructionFixture()
+    try fixture.write("Checks.\n", to: fixture.project.appendingPathComponent("CONTRIBUTING.md"))
+    try fixture.own("guide", body: "Run [the checks](CONTRIBUTING.md#local).")
+    try fixture.addOwn(names: ["guide"])
+    try fixture.own("missing", body: "Read [notes](notes.md).")
+    #expect(throws: InstructionError.self) { try fixture.addOwn(names: ["missing"]) }
+    try fixture.write("x\n", to: fixture.project.appendingPathComponent("vendor/lib/README.md"))
+    try fixture.write(
+      "gitdir: elsewhere\n", to: fixture.project.appendingPathComponent("vendor/lib/.git"))
+    try fixture.own("vendor", body: "Read [lib](vendor/lib/README.md).")
+    #expect(throws: InstructionError.self) { try fixture.addOwn(names: ["vendor"]) }
+    try fixture.own("outside", body: "Read [up](../home/x.md).")
+    #expect(throws: InstructionError.self) { try fixture.addOwn(names: ["outside"]) }
+    try fixture.section("linked", body: "See [guide](guide.md).")
+    try fixture.commit()
+    #expect(throws: InstructionError.self) {
+      try fixture.add(names: ["linked"], scope: .user, agents: [.codex])
+    }
+    #expect(
+      try fixture.text() == generated(["# guide\n\nRun [the checks](CONTRIBUTING.md#local)."]))
+  }
+
+  @Test func exportMapsTargetsToSectionsWithoutWriting() throws {
+    let fixture = try InstructionFixture()
+    try FileManager.default.createDirectory(
+      at: fixture.project.appendingPathComponent("Sources"), withIntermediateDirectories: true)
+    try fixture.section("shared")
+    try fixture.commit()
+    try fixture.add(scope: .user, agents: [.codex])
+    try fixture.own("guide")
+    try fixture.own("sources", paths: ["Sources/**"])
+    try fixture.addOwn(names: ["guide", "sources"], agents: [.codex])
+    let empty = fixture.root.appendingPathComponent("empty")
+    try FileManager.default.createDirectory(at: empty, withIntermediateDirectories: true)
+    let before = try fixture.snapshot()
+    let mappings = InstructionOperations.export(
+      projectRoots: [fixture.project, empty, fixture.project], environment: fixture.environment)
+    #expect(mappings.map(\.scope) == [.user, .project, .project])
+    #expect(mappings[0].targets.map(\.target) == ["~/.codex/AGENTS.md"])
+    #expect(mappings[0].targets[0].sections.map(\.name) == ["shared"])
+    let project = mappings[1]
+    #expect(project.status == .locked)
+    #expect(project.targets.map(\.target) == ["AGENTS.md", "Sources/AGENTS.md"])
+    #expect(project.targets.map { $0.sections.map(\.name) } == [["guide"], ["sources"]])
+    #expect(mappings[2].status == .missingLock)
+    #expect(try fixture.snapshot() == before)
+  }
+}
diff --git a/Tests/AgentsInstructionsTests/UnitFormatTests.swift b/Tests/AgentsInstructionsTests/UnitFormatTests.swift
new file mode 100644
index 0000000..3dfa143
--- /dev/null
+++ b/Tests/AgentsInstructionsTests/UnitFormatTests.swift
@@ -0,0 +1,104 @@
+import AgentsInstructions
+import Foundation
+import Testing
+
+func unit(_ text: String, id: String = "rules:care") throws -> InstructionSection {
+  try Instructions.validateSource(Data(text.utf8), id: id)
+}
+
+@Suite("Instructions file format")
+struct UnitFormatTests {
+  @Test func readsFrontMatterAndKeepsTheBodyAsWritten() throws {
+    let section = try unit(
+      "---\ndescription: Flag unsupported claims.\n---\n\n## Code Review Rules\n\n### Claims\n\n- Flag claims.\n\n\n"
+    )
+    #expect(section.description == "Flag unsupported claims.")
+    #expect(section.level == 2)
+    #expect(section.heading == "Code Review Rules")
+    #expect(section.paths.isEmpty)
+    #expect(section.directory.isEmpty)
+    #expect(
+      try Instructions.render([section])
+        == generated(["## Code Review Rules\n\n### Claims\n\n- Flag claims."]))
+  }
+
+  @Test func scopesPathsAfterTheFirstHeading() throws {
+    let section = try unit(
+      "---\ndescription: Rendering.\npaths:\n  - \"Sources/Render/**/*.swift\"\n  - Sources/Render/Shaders/**\n---\n# Rendering\nKeep frames stable.\n"
+    )
+    #expect(section.paths == ["Sources/Render/**/*.swift", "Sources/Render/Shaders/**"])
+    #expect(section.directory == "Sources/Render")
+    #expect(
+      try Instructions.render([section])
+        == generated([
+          "# Rendering\n\nApplies when working on files matching `Sources/Render/**/*.swift`, `Sources/Render/Shaders/**`.\n\nKeep frames stable."
+        ]))
+    let headingOnly = try unit(
+      "---\ndescription: d\npaths: [\"Docs/**\"]\n---\n# Docs\n")
+    #expect(
+      try Instructions.render([headingOnly])
+        == generated(["# Docs\n\nApplies when working on files matching `Docs/**`."]))
+  }
+
+  @Test(arguments: [
+    (["Sources/**/*.swift"], "Sources"), (["Sources/A/**", "Sources/B/**"], "Sources"),
+    (["**/*.swift"], ""), (["Docs/guide.md"], "Docs"), (["a/b/c.md", "a/b/d/**"], "a/b"),
+    (["a/b/**", "c/**"], ""), (["a?/b/**"], ""),
+  ])
+  func placesSectionsInTheSharedLiteralDirectory(_ paths: [String], _ directory: String) {
+    #expect(Instructions.directory(for: paths) == directory)
+  }
+
+  @Test(arguments: [
+    "description: \"Quoted: value\"\n", "description: 'It''s quoted'\n",
+    "# comment\ndescription: Plain text\n\n",
+  ])
+  func acceptsTheDocumentedScalarForms(_ front: String) throws {
+    let section = try unit("---\n" + front + "---\n# Rules\n")
+    #expect(!section.description.isEmpty)
+    #expect(!section.description.hasPrefix("\"") && !section.description.hasPrefix("'"))
+  }
+
+  @Test(arguments: [
+    "# Rules\n", "---\ndescription: d\n# Rules\n", "---\n---\n# Rules\n",
+    "---\ndescription:\n---\n# Rules\n", "---\ndescription: d\ntitle: t\n---\n# Rules\n",
+    "---\ndescription: d\ndescription: e\n---\n# Rules\n", "---\ndescription: a: b\n---\n# Rules\n",
+    "---\ndescription: [d]\n---\n# Rules\n", "---\ndescription: d\npaths: []\n---\n# Rules\n",
+    "---\ndescription: d\npaths: ['a/**']\n---\n# Rules\n",
+    "---\ndescription: d\npaths:\n---\n# Rules\n", "---\n description: d\n---\n# Rules\n",
+  ])
+  func rejectsInvalidFrontMatter(_ text: String) {
+    #expect(throws: InstructionError.self) { try unit(text) }
+  }
+
+  @Test(arguments: ["../outside/**", "/absolute/**", "a//b", "a/./b", "a/**b/c", "a/[x]", "a/{b}"])
+  func rejectsInvalidPathPatterns(_ pattern: String) {
+    #expect(throws: InstructionError.self) {
+      try unit("---\ndescription: d\npaths: [\"\(pattern)\"]\n---\n# Rules\n")
+    }
+  }
+
+  @Test(arguments: [
+    "Text first.\n# Rules\n", "Rules\n=====\n", "## Rules\n# Higher\n", "## Rules\n## Same\n",
+    "# Rules\n\n> Quoted\n> ---\n", "# Rules\n```\nopen\n", "# Rules\n
\nopen\n", "", + ]) + func rejectsBodiesWithoutOneLeadingHeading(_ body: String) { + #expect(throws: InstructionError.self) { try unit("---\ndescription: d\n---\n" + body) } + } + + @Test func acceptsByteOrderMarkAndCRLFAndHashesOriginalBytes() throws { + let plain = Data("---\ndescription: d\n---\n# Rules\nBody\n".utf8) + let crlf = + Data([0xEF, 0xBB, 0xBF]) + Data("---\r\ndescription: d\r\n---\r\n# Rules\r\nBody\r\n".utf8) + let first = try Instructions.validateSource(plain, id: "a") + let second = try Instructions.validateSource(crlf, id: "a") + #expect(try Instructions.render([first]) == Instructions.render([second])) + #expect(first.hash != second.hash) + } + + @Test func rejectsInvalidUTF8() { + #expect(throws: InstructionError.invalidUTF8) { + try Instructions.validateSource(Data([0xFF]), id: "bad") + } + } +} diff --git a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift index 10b731b..dc0eab5 100644 --- a/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift +++ b/Tests/AgentsSkillsTests/AutomaticSelectionTests.swift @@ -11,7 +11,8 @@ struct AutomaticSelectionTests { try fixture.skill("demo", body: "Original") let instructions = fixture.repo.appendingPathComponent("instructions") try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) - try Data("# Demo\n\nOriginal\n".utf8).write(to: instructions.appendingPathComponent("demo.md")) + try Data("---\ndescription: Fixture instructions.\n---\n# Demo\n\nOriginal\n".utf8).write( + to: instructions.appendingPathComponent("demo.md")) try fixture.commit() let store = fixture.store() try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) @@ -62,7 +63,7 @@ struct AutomaticSelectionTests { at: instructions.appendingPathComponent("demo.md"), to: instructions.appendingPathComponent("replacement.md")) } else { - try Data("# Demo\n\nCurrent\n".utf8).write( + try Data("---\ndescription: Fixture instructions.\n---\n# Demo\n\nCurrent\n".utf8).write( to: instructions.appendingPathComponent("demo.md")) } try fixture.commit() diff --git a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift index 9708683..3f965da 100644 --- a/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift +++ b/Tests/AgentsSkillsTests/ReadOnlyInspectionTests.swift @@ -140,8 +140,9 @@ struct ReadOnlyInspectionTests { let instructions = fixture.repo.appendingPathComponent("instructions") try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) for name in ["one", "two"] { - try Data("# \(name)\n\nInstructions\n".utf8).write( - to: instructions.appendingPathComponent(name + ".md")) + try Data("---\ndescription: Fixture instructions.\n---\n# \(name)\n\nInstructions\n".utf8) + .write( + to: instructions.appendingPathComponent(name + ".md")) } try fixture.commit() for directory in [fixture.environment.projectDirectory, fixture.environment.homeDirectory] { @@ -206,8 +207,9 @@ struct ReadOnlyInspectionTests { let instructions = fixture.repo.appendingPathComponent("instructions") try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) for name in ["one", "two"] { - try Data("# \(name)\n\nInstructions\n".utf8).write( - to: instructions.appendingPathComponent(name + ".md")) + try Data("---\ndescription: Fixture instructions.\n---\n# \(name)\n\nInstructions\n".utf8) + .write( + to: instructions.appendingPathComponent(name + ".md")) } try fixture.commit() let revision = try fixture.head() @@ -292,7 +294,7 @@ struct ReadOnlyInspectionTests { try fixture.skill("demo", body: "Original") let instructions = fixture.repo.appendingPathComponent("instructions") try FileManager.default.createDirectory(at: instructions, withIntermediateDirectories: true) - try Data("# Rules\n\nInstructions\n".utf8).write( + try Data("---\ndescription: Fixture instructions.\n---\n# Rules\n\nInstructions\n".utf8).write( to: instructions.appendingPathComponent("rules.md")) try fixture.commit() let source = SourceDeclaration( diff --git a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift index 3c418d0..5d080ee 100644 --- a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift +++ b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift @@ -148,6 +148,21 @@ struct WatchSubscriptionTests { #expect(Set(status.changes.map(\.name)) == ["inside", "rule"]) } + @Test func namesNestedInstructionsByTheirContainerPath() throws { + let fixture = try SkillFixture() + try write(fixture.repo.appendingPathComponent("instructions/epd/review.md"), "old") + try write(fixture.repo.appendingPathComponent("instructions/notes.txt"), "ignored") + try fixture.commit() + let watch = SkillOperations.watchOperations() + try watch.add(fixture.repo.path, alias: "source", environment: fixture.environment) + try write(fixture.repo.appendingPathComponent("instructions/epd/review.md"), "new") + try write(fixture.repo.appendingPathComponent("instructions/notes.txt"), "still ignored") + try fixture.commit() + let status = try #require(watch.status(environment: fixture.environment).first) + #expect(status.changes.map(\.name) == ["epd/review"]) + #expect(status.changes.first?.newPath == "instructions/epd/review.md") + } + @Test func retainsSeenHistoryAcrossForcePushAndMirrorGarbageCollection() throws { let fixture = try SkillFixture() try fixture.skill("old", body: "old") diff --git a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift index ae578b5..c55bffc 100644 --- a/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift +++ b/Tests/AgentsUpdatesTests/CombinedUpdateTests.swift @@ -49,6 +49,21 @@ struct CombinedUpdateTests { #expect(try !fixture.preview().hasChanges) } + @Test func combinedApplyStopsBeforeWritingOverAHandWrittenTarget() throws { + let fixture = try UpdateFixture() + try fixture.install(agents: [.codex]) + try fixture.write("Hand written.\n", to: fixture.instruction(.geminiCLI)) + var declaration = try fixture.store.loadDeclaration() + declaration.instructions?.agents = [.codex, .geminiCLI] + try fixture.store.save(declaration: declaration, resolved: fixture.store.loadResolved()) + let preview = try fixture.preview() + #expect(preview.instructions.targets.contains { $0.target == "GEMINI.md" && $0.foreign }) + let before = try fixture.snapshot() + #expect(throws: InstructionError.unownedTargets(["GEMINI.md"])) { try fixture.apply() } + #expect(try fixture.snapshot() == before) + #expect(try fixture.bytes(fixture.instruction(.geminiCLI)) == Data("Hand written.\n".utf8)) + } + @Test(arguments: [false, true]) func standaloneInstructionsValidateRetainedSkills(_ apply: Bool) throws { let fixture = try UpdateFixture() @@ -392,7 +407,7 @@ struct CombinedUpdateTests { #expect(try fixture.preview().hasChanges) } - @Test(arguments: ["skills", "instructions", "assembly"]) + @Test(arguments: ["skills", "instructions", "target"]) func preparationFailureNeverExposesAPartialReport(_ kind: String) throws { let fixture = try UpdateFixture() try fixture.install() @@ -407,9 +422,9 @@ struct CombinedUpdateTests { try fixture.write("invalid", to: fixture.repo.appendingPathComponent("instructions/rules.md")) try fixture.commit() } else { - try fixture.write( - "\nbroken", - to: fixture.instruction()) + try FileManager.default.removeItem(at: fixture.instruction()) + try FileManager.default.createDirectory( + at: fixture.instruction(), withIntermediateDirectories: false) } let before = try fixture.snapshot() var called = false @@ -548,7 +563,8 @@ struct CombinedUpdateTests { #expect(prompt.instructions.changedPrompts.isEmpty) _ = try fixture.apply() try fixture.write( - "# Second\n\nSecond body\n", to: fixture.repo.appendingPathComponent("instructions/second.md") + "---\ndescription: Fixture instructions.\n---\n# Second\n\nSecond body\n", + to: fixture.repo.appendingPathComponent("instructions/second.md") ) try fixture.commit() declaration.instructions?.chatgpt?["weekly"]?.sections = ["fixture:rules", "fixture:second"] diff --git a/Tests/AgentsUpdatesTests/UpdateFixture.swift b/Tests/AgentsUpdatesTests/UpdateFixture.swift index cca05e5..7d0b8fe 100644 --- a/Tests/AgentsUpdatesTests/UpdateFixture.swift +++ b/Tests/AgentsUpdatesTests/UpdateFixture.swift @@ -58,7 +58,9 @@ final class UpdateFixture { "---\nname: demo\ndescription: fixture\n---\n\n\(text)\n", to: repo.appendingPathComponent("skills/demo/SKILL.md")) try write("#!/bin/sh\necho fixture\n", to: repo.appendingPathComponent("skills/demo/run.sh")) - try write("# Rules\n\n\(text)\n", to: repo.appendingPathComponent("instructions/rules.md")) + try write( + "---\ndescription: Fixture instructions.\n---\n# Rules\n\n\(text)\n", + to: repo.appendingPathComponent("instructions/rules.md")) } func commit() throws { From 1c6f567e578ecc925832836493b848dbc5ae5408 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:28:43 +0800 Subject: [PATCH 02/18] fix(instructions): align doctor, install and init with own files - Doctor reports any difference from a locked target as drift; the lock owns the file whether or not the notice line remains. - Restoring a lock stops with InstructionError.ownChanged when a project's own instructions file changed since the lock. - initializeInstructions(named:environment:) creates .agent/instructions/.md under the project's state lock instead of writing into an arbitrary directory with its own lock. --- CHANGELOG.md | 15 +++++++---- Documentation/Architecture/Instructions.md | 13 +++++----- Documentation/Architecture/State.md | 3 ++- README.md | 3 ++- Sources/AgentsCore/TransactionPaths.swift | 25 ++++++++++--------- .../InstructionDoctor.swift | 4 +-- .../InstructionLifecycleModels.swift | 1 - .../InstructionModels.swift | 3 +++ .../InstructionOperations.swift | 14 ++++++----- .../InstructionSources.swift | 5 +--- .../InstructionTransactionTests.swift | 11 ++++++++ .../DoctorLifecycleTests.swift | 4 +-- .../LifecycleTests.swift | 19 ++++++++++---- .../TargetLifecycleTests.swift | 2 +- 14 files changed, 75 insertions(+), 47 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a848df..95095b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,14 +13,15 @@ publication follows the [release checklist](Documentation/Reference/Release.md). as `epd/review`. - A project's own instructions in `.agent/instructions/` are selected by bare name and read from the working tree. `InstructionAddOptions(source: ".")` - adds them; `listOwn(environment:)` lists them. + adds them; `listOwn(environment:)` lists them. Restoring a lock fails with + `InstructionError.ownChanged` when an own file changed since the lock. - Front matter `paths` scopes a section: its patterns are named after its first heading, and in project scope the section is written to the `AGENTS.md` of the directory the patterns share. - `InstructionOperations.export(projectRoots:environment:)` maps the locked targets of the user scope and given projects to their sections. -- Doctor reports hand-written files in target locations, own files changed - since the lock, and links in generated targets that no longer resolve. +- Doctor reports own files changed since the lock and links in generated + targets that no longer resolve. ### Changed @@ -34,8 +35,12 @@ publication follows the [release checklist](Documentation/Reference/Release.md). generate needs `replace`; `InstructionError.unownedTargets` names it. - **Breaking:** `InstructionTargetChange.assembly` is replaced by `foreign`, and `InstructionDrift` is `clean`, `drifted` or `missing`. Diagnostic kinds - `missingBlock`, `adoption` and `conflict` become `missingTarget`, - `foreignTarget`, `ownChanged` and `invalidLink`. + `missingBlock`, `adoption` and `conflict` are removed; `missingTarget`, + `ownChanged` and `invalidLink` are added. +- **Breaking:** `initializeInstructions(named:environment:)` replaces + `initializeInstructions(named:directory:)` and creates + `.agent/instructions/.md` in the project, using the project's state + lock. - A local link in a section must resolve, from the target, to a file in the checkout being written; user targets accept no local links. - A target that no longer receives sections is deleted only while it equals its diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 29c2696..19e6b61 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -38,8 +38,9 @@ revision, path and original-byte hash. Source containers cannot hold targets. A project's own files live in `.agent/instructions/` and are referenced by bare name; `alias:name` references a declared source. Own files are read from the working tree as it is. Their lock records have source `.`, the project-relative -path and the hash, and no revision. Restoring a lock fails when an own file's -hash changed; update reads the current file. +path and the hash, and no revision. Restoring a lock fails with +`InstructionError.ownChanged` when an own file's hash changed; update reads the +current file. `add(InstructionAddOptions, beforeApply:)` accepts a source alias or string, or `.` for own files, plus an optional alias, requirement, search path, ordered @@ -117,7 +118,7 @@ Ancestor files are reported and never modified. | `installResolvedReport(scope:environment:)` | Restore locked renderings without changing state bytes | | `remove(names:scope:agents:environment:beforeApply:)` | Remove sections from file and prompt selections and lock records | | `renderChatGPT(prompt:scope:environment:)` | Return locked sections followed by the prompt's current custom file | -| `initializeInstructions(named:directory:)` | Create a validated `.md` with front matter, refusing an existing entry | +| `initializeInstructions(named:environment:)` | Create a validated `.agent/instructions/.md` with front matter, refusing an existing entry | | `doctor(scope:environment:codexConfiguration:)` | Inspect one scope and compare sections against the other scope | | `doctor(projectRoots:environment:codexConfiguration:)` | Audit explicit project roots without writing | | `export(projectRoots:environment:)` | Map the user scope's and each root's locked targets to their sections without writing | @@ -153,9 +154,9 @@ files, forwarding files, declaration, lock and cache pruning. Exact source materializations are verified and published through cache transactions before the target/state transaction. The journal has fixed project instruction paths, nested project `AGENTS.md` and `GEMINI.md` paths, configured user instruction -roots and an authoring root restricted to named Markdown files. Initialization -uses a project state lock and journal in the supplied directory without -creating a declaration or resolved file. +roots and new top-level named Markdown files in `.agent/instructions/`. +Initialization uses the project's state lock and journal without creating a +declaration or resolved file. Read operations take an existing shared scope lock without creating one or replaying recovery. Pending recovery stops listings and previews. Doctor reports diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 2a60814..94c3967 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -110,7 +110,8 @@ A durable `transaction.json` in the scope state directory records target, state file and pruning replacements before mutation. Paths are relative to named roots in that scope: `state`, registered agent installation directories, and registered instruction destinations. Instruction roots permit fixed project -files, configured user files and named Markdown authoring files. The +files, configured user files and named Markdown files in the project's own +instructions container. The journal binds the state directory and each used root to its physical location and filesystem identity. Configured agent containers are resolved at the registry boundary; recovery opens journal descendants without following links. diff --git a/README.md b/README.md index 02128f4..928fe51 100644 --- a/README.md +++ b/README.md @@ -220,7 +220,8 @@ by bare name. `InstructionOperations` generates whole target files from them: Its `projectRoots` overload audits explicit projects without writing. - `export(projectRoots:...)` reads the user lock and the given projects' locks into a mapping of targets to sections, without writing. -- `initializeInstructions(named:directory:)` creates a valid file skeleton. +- `initializeInstructions(named:environment:)` creates a valid file skeleton in + the project's `.agent/instructions/`. A target is a notice line followed by the sections in declared order. A section with `paths` gets a line naming its patterns and, in project scope, is written diff --git a/Sources/AgentsCore/TransactionPaths.swift b/Sources/AgentsCore/TransactionPaths.swift index f292eff..6a6b34e 100644 --- a/Sources/AgentsCore/TransactionPaths.swift +++ b/Sources/AgentsCore/TransactionPaths.swift @@ -16,13 +16,8 @@ struct TransactionPaths { if InstructionLocations.isProjectTarget(relative) { return "instructions-project/" + relative } - if destination.deletingLastPathComponent().standardizedFileURL - == base.resolvingSymlinksInPath(), - destination.pathExtension == "md", - destination.deletingPathExtension().lastPathComponent - == PathSafety.sanitizeName(destination.deletingPathExtension().lastPathComponent) - { - return "instructions-authoring/" + destination.lastPathComponent + if isAuthoringFile(relative.split(separator: "/").map(String.init)) { + return "instructions-authoring/" + relative } } else { for agent in AgentID.allCases { @@ -85,6 +80,14 @@ struct TransactionPaths { return try DirectoryHandle(at: url, create: create, checkpoint: checkpoint) } + /// A top-level file in the project's own instructions container, `.agent/instructions/.md`. + private func isAuthoringFile(_ components: [String]) -> Bool { + guard components.count == 3, components[0] == store.directory.lastPathComponent, + components[1] == "instructions", components[2].hasSuffix(".md") + else { return false } + return Declaration.isInstructionName(String(components[2].dropLast(3))) + } + func components(_ path: String) throws -> (root: String, descendants: [String]) { let parts = path.split(separator: "/", omittingEmptySubsequences: false).map(String.init) guard parts.count >= 2, @@ -110,11 +113,9 @@ struct TransactionPaths { throw CoreError.unsafePath("unmanaged project instruction path") } } else if key == "instructions-authoring", store.scope == .project { - let file = URL(fileURLWithPath: descendants[0]) - guard descendants.count == 1, file.pathExtension == "md", - file.deletingPathExtension().lastPathComponent - == PathSafety.sanitizeName(file.deletingPathExtension().lastPathComponent) - else { throw CoreError.unsafePath("invalid instruction authoring path") } + guard isAuthoringFile(descendants) else { + throw CoreError.unsafePath("invalid instruction authoring path") + } } else if key.hasPrefix("instructions-"), store.scope == .user, let agent = AgentID(rawValue: String(key.dropFirst("instructions-".count))), let file = InstructionLocations.file(for: agent, scope: .user, environment: store.environment) diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index fa8c4db..b0927b0 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -82,9 +82,7 @@ extension InstructionOperations { } continue } - if let bytes, !Instructions.isGenerated(bytes) { - report(.foreignTarget, "Target file was not generated by agents.", file) - } else if let bytes, Instructions.hash(bytes) != target.blockHash { + if let bytes, Instructions.hash(bytes) != target.blockHash { report(.drift, "Generated instructions differ from their lock.", file) } else if bytes == nil { report(.missingTarget, "Generated instructions file is missing.", file) diff --git a/Sources/AgentsInstructions/InstructionLifecycleModels.swift b/Sources/AgentsInstructions/InstructionLifecycleModels.swift index 3d97b97..744a6be 100644 --- a/Sources/AgentsInstructions/InstructionLifecycleModels.swift +++ b/Sources/AgentsInstructions/InstructionLifecycleModels.swift @@ -97,7 +97,6 @@ public struct InstructionDiagnostic: Sendable, Equatable { public enum Kind: String, Sendable { case missingTarget case drift - case foreignTarget case ownChanged case invalidLink case invalidTarget diff --git a/Sources/AgentsInstructions/InstructionModels.swift b/Sources/AgentsInstructions/InstructionModels.swift index 187e035..22fb9fb 100644 --- a/Sources/AgentsInstructions/InstructionModels.swift +++ b/Sources/AgentsInstructions/InstructionModels.swift @@ -59,6 +59,7 @@ public enum InstructionError: Error, Sendable, Equatable, CustomStringConvertibl case invalidLockedBlock case invalidLinks([InstructionLinkProblem]) case unownedTargets([String]) + case ownChanged(name: String) case emptyPrompt public var description: String { @@ -86,6 +87,8 @@ public enum InstructionError: Error, Sendable, Equatable, CustomStringConvertibl case .unownedTargets(let targets): return "Files that agents did not generate are in the way: \(targets.joined(separator: ", "))." + case .ownChanged(let name): + return "Own instructions file '\(name)' changed since the lock." case .emptyPrompt: return "A ChatGPT prompt must have at least one locked section." } diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 91556e9..e15e8ae 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -285,19 +285,21 @@ public enum InstructionOperations { } } - /// Creates `.md` with the required front matter in the supplied directory, without - /// replacing an existing entry. + /// Creates the project's own `.agent/instructions/.md` with the required front matter, + /// without replacing an existing entry or creating a declaration or lock. @discardableResult - public static func initializeInstructions(named name: String, directory: URL) throws -> URL { + public static func initializeInstructions( + named name: String, environment: RuntimeEnvironment = RuntimeEnvironment() + ) throws -> URL { guard Declaration.isInstructionName(name), !name.contains("/") else { throw CoreError.invalidSource( "instruction names use lowercase letters, digits and hyphens: \(name)") } - let environment = RuntimeEnvironment( - projectDirectory: directory, homeDirectory: directory, environment: [:]) let store = StateStore(scope: .project, environment: environment) return try store.withLock { - let file = directory.resolvingSymlinksInPath().appendingPathComponent(name + ".md") + let file = environment.projectDirectory.resolvingSymlinksInPath() + .appendingPathComponent(InstructionSources.ownContainer) + .appendingPathComponent(name + ".md") guard try InstructionTargets.read(file) == nil else { throw CoreError.invalidSource("instruction file already exists: \(file.path)") } diff --git a/Sources/AgentsInstructions/InstructionSources.swift b/Sources/AgentsInstructions/InstructionSources.swift index bcd600c..31d6906 100644 --- a/Sources/AgentsInstructions/InstructionSources.swift +++ b/Sources/AgentsInstructions/InstructionSources.swift @@ -118,10 +118,7 @@ final class InstructionSources { if record.source == Self.own { guard let unit = try own().first(where: { $0.record.path == record.path }), unit.record.hash == record.hash - else { - throw CoreError.invalidState( - "own instructions file changed since the lock: \(record.name); run 'agents update'") - } + else { throw InstructionError.ownChanged(name: record.name) } return unit } guard let source = sources[record.source], let revision = record.revision, diff --git a/Tests/AgentsCoreTests/InstructionTransactionTests.swift b/Tests/AgentsCoreTests/InstructionTransactionTests.swift index e3ca039..e28f640 100644 --- a/Tests/AgentsCoreTests/InstructionTransactionTests.swift +++ b/Tests/AgentsCoreTests/InstructionTransactionTests.swift @@ -70,6 +70,17 @@ struct InstructionTransactionTests { try paths.components("instructions-project/Sources/Render/AGENTS.md") } #expect(throws: Never.self) { try paths.components("instructions-project/Sources/GEMINI.md") } + #expect(throws: Never.self) { + try paths.components("instructions-authoring/.agent/instructions/new-rules.md") + } + for path in [ + "instructions-authoring/new-rules.md", "instructions-authoring/.agent/new-rules.md", + "instructions-authoring/.agent/instructions/epd/review.md", + "instructions-authoring/.agent/instructions/Rules.md", + "instructions-authoring/.agent/instructions/notes.txt", + ] { + #expect(throws: (any Error).self) { try paths.components(path) } + } let outside = root.appendingPathComponent("outside") try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) try Data("owner".utf8).write(to: outside.appendingPathComponent("CLAUDE.md")) diff --git a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift index b20303f..3e0f971 100644 --- a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift @@ -118,7 +118,7 @@ struct InstructionDoctorTests { #expect(!report.diagnostics.contains { $0.kind == .invalidConfiguration }) } - @Test func doctorReportsForeignAndDriftedTargetsWithoutWriting() throws { + @Test func doctorReportsEveryDifferenceFromALockedTargetAsDrift() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() @@ -127,7 +127,7 @@ struct InstructionDoctorTests { try fixture.write("# rules\n\nOriginal\n", to: file) #expect( try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { - $0.kind == .foreignTarget && $0.path == file + $0.kind == .drift && $0.path == file }) try fixture.write(generated(["# rules\n\nCustom"]), to: file) let report = try InstructionOperations.doctor(environment: fixture.environment) diff --git a/Tests/AgentsInstructionsTests/LifecycleTests.swift b/Tests/AgentsInstructionsTests/LifecycleTests.swift index 5ef2025..80817f1 100644 --- a/Tests/AgentsInstructionsTests/LifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleTests.swift @@ -369,19 +369,28 @@ struct InstructionLifecycleTests { } } - @Test func initializeCreatesValidatedSkeletonAndNeverOverwrites() throws { + @Test func initializeCreatesAnOwnSkeletonAndNeverOverwrites() throws { let fixture = try InstructionFixture() let file = try InstructionOperations.initializeInstructions( - named: "new-rules", directory: fixture.repo.appendingPathComponent("instructions")) + named: "new-rules", environment: fixture.environment) + #expect( + file.path + == fixture.project.resolvingSymlinksInPath() + .appendingPathComponent(".agent/instructions/new-rules.md").path) let section = try Instructions.validateSource(Data(contentsOf: file), id: "new-rules") #expect(section.heading == "new-rules") #expect(section.level == 1) + #expect(try InstructionOperations.listOwn(environment: fixture.environment).count == 1) + #expect(!FileManager.default.fileExists(atPath: fixture.store().declarationURL.path)) #expect(throws: (any Error).self) { try InstructionOperations.initializeInstructions( - named: "new-rules", directory: file.deletingLastPathComponent()) + named: "new-rules", environment: fixture.environment) } - #expect(throws: (any Error).self) { - try InstructionOperations.initializeInstructions(named: "../escape", directory: fixture.repo) + for name in ["../escape", "nested/name", "Upper"] { + #expect(throws: (any Error).self) { + try InstructionOperations.initializeInstructions( + named: name, environment: fixture.environment) + } } } } diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index 4e55a24..de9338b 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -34,7 +34,7 @@ struct TargetLifecycleTests { try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { $0.kind == .ownChanged }) - #expect(throws: (any Error).self) { + #expect(throws: InstructionError.ownChanged(name: "guide")) { try InstructionOperations.installResolvedReport(environment: fixture.environment) } _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) From f7125ce69a4e7e6f7e0b835bd30bd57d01fe3b54 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:06:00 +0800 Subject: [PATCH 03/18] fix(instructions): own targets by their notice and harden placement - A file is owned when it is blank or starts with the notice; a lock entry alone no longer is, so a 0.1.2 target with custom content needs replace, and install, remove and doctor treat it as foreign. - Install restores the locked targets and Claude import files instead of recomputing forwarding. - Nested target directories cannot be symbolic links, .git, or inside another repository; local links resolve symbolic links before '..'. - Own instructions are read by name for resolution and restore; a symbolic link at or below a search path is an error; discovery skips AGENTS.md and GEMINI.md. - Removing a name equal to a declared reference removes that reference. - Doctor covers own files used only by prompts, checks root forwarding only for a root Claude target, and reports Claude files that hide a nested AGENTS.md. - Export places user sections without their content. - A declaration may omit sources, and an unchanged declaration is not rewritten. --- CHANGELOG.md | 21 +- Documentation/Architecture/Instructions.md | 52 +++-- Documentation/Architecture/Package.md | 10 +- Documentation/Architecture/State.md | 11 +- Documentation/Proposals/AgentInstructions.md | 18 +- README.md | 2 +- Sources/AgentsCore/Declaration.swift | 13 ++ Sources/AgentsCore/InstructionLocations.swift | 7 +- Sources/AgentsCore/StateStore.swift | 12 +- Sources/AgentsCore/WatchOperations.swift | 3 +- .../InstructionDoctor.swift | 39 +++- .../InstructionExport.swift | 15 +- .../InstructionLifecycleModels.swift | 1 + .../InstructionOperations.swift | 19 +- .../InstructionSources.swift | 46 +++- .../InstructionTargets.swift | 75 +++++-- Sources/AgentsInstructions/Instructions.swift | 12 +- .../AgentsInstructions/MarkdownDocument.swift | 52 +---- Sources/AgentsSkills/SkillLifecycle.swift | 3 +- Sources/AgentsSkills/SkillOperations.swift | 3 +- Sources/AgentsUpdates/UpdatePlan.swift | 5 +- .../DoctorLifecycleTests.swift | 4 +- .../LifecycleSafetyTests.swift | 3 +- .../LifecycleTests.swift | 10 +- .../OwnershipAndPlacementTests.swift | 197 ++++++++++++++++++ .../TargetLifecycleTests.swift | 17 ++ 26 files changed, 501 insertions(+), 149 deletions(-) create mode 100644 Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 95095b8..97fb8e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,18 +31,33 @@ publication follows the [release checklist](Documentation/Reference/Release.md). - **Breaking:** targets are generated in full: a notice line followed by the sections. Custom content in targets, managed blocks, title detection, heading offsets and adoption of matching custom sections are gone. Move hand-written - content into instructions files. Writing over a file that agents did not - generate needs `replace`; `InstructionError.unownedTargets` names it. + content into instructions files. A file is owned when it is blank or starts + with the notice; writing over any other file needs `replace`, and + `InstructionError.unownedTargets` names it. Upgrading from 0.1.2 therefore + takes over targets that kept custom content only with `replace`. - **Breaking:** `InstructionTargetChange.assembly` is replaced by `foreign`, and `InstructionDrift` is `clean`, `drifted` or `missing`. Diagnostic kinds `missingBlock`, `adoption` and `conflict` are removed; `missingTarget`, - `ownChanged` and `invalidLink` are added. + `foreignTarget`, `ownChanged` and `invalidLink` are added. - **Breaking:** `initializeInstructions(named:environment:)` replaces `initializeInstructions(named:directory:)` and creates `.agent/instructions/.md` in the project, using the project's state lock. +- A declaration may omit `sources`. Operations that leave a declaration's + content unchanged no longer rewrite `agents.json`, so a committed + declaration keeps its formatting. - A local link in a section must resolve, from the target, to a file in the checkout being written; user targets accept no local links. +- Removing a name that equals a declared reference removes that reference, so + an own file's bare name no longer collides with a source's same-named file. +- Install restores the locked Claude import files instead of recomputing them. +- A nested target's directory cannot be a symbolic link, `.git`, or inside + another repository. Discovery skips `AGENTS.md` and `GEMINI.md` in + containers, and a symbolic link at or below a source's search path is an + error. +- Doctor reports a Claude file that keeps Claude Code from reading a generated + nested `AGENTS.md`, and checks root forwarding only when the root + `AGENTS.md` is a Claude target. - A target that no longer receives sections is deleted only while it equals its locked rendering. diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 19e6b61..93a116f 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -29,7 +29,9 @@ and a pattern that starts with a wildcard yields the project root. Discovery reads `.md` files below `instructions/` and `.agents/instructions/` of the source's search `path`, recursively. A name is the container-relative path without `.md`; each segment uses lowercase letters, digits and hyphens. -Symbolic links, invalid names and a name in both containers are errors. +`AGENTS.md` and `GEMINI.md` are target names, so discovery skips them; a +project can scope sections to its own container. A symbolic link at or below +the search path, an invalid name and a name in both containers are errors. Instructions require Git sources. Local sources identify the repository root; use `path` to move its search root. Discovery reads committed trees even when the working tree is dirty. Each section and prompt section has its own @@ -38,9 +40,10 @@ revision, path and original-byte hash. Source containers cannot hold targets. A project's own files live in `.agent/instructions/` and are referenced by bare name; `alias:name` references a declared source. Own files are read from the working tree as it is. Their lock records have source `.`, the project-relative -path and the hash, and no revision. Restoring a lock fails with -`InstructionError.ownChanged` when an own file's hash changed; update reads the -current file. +path and the hash, and no revision. Resolution and restore read only the named +file, `.agent/instructions/.md`, so other files in the container do not +affect them. Restoring a lock fails with `InstructionError.ownChanged` when an +own file's hash changed; update reads the current file. `add(InstructionAddOptions, beforeApply:)` accepts a source alias or string, or `.` for own files, plus an optional alias, requirement, search path, ordered @@ -74,19 +77,23 @@ document heading. In project scope, sections are grouped by `directory`: each group renders into the `AGENTS.md`, or `GEMINI.md`, of that directory, which must already exist. +No component of a nested target's directory may be a symbolic link or `.git`, +or hold another repository or worktree. User scope renders all sections into each recipient's file. Project keys are relative to the project root, and a nested key names `AGENTS.md` or `GEMINI.md` -in a directory outside `.git` and `.agent`; user keys are `~/`-relative to the +in a directory outside any `.git` and the top-level `.agent`; user keys are `~/`-relative to the supplied home, and configured user locations outside home use absolute keys. Locked destinations must remain registered instruction locations in the runtime environment; lock contents cannot authorize arbitrary writes. Configured user containers may resolve through symlinks. Journal validation opens project descendants without following links. -A file is owned when the lock records it or `Instructions.isGenerated` finds the -notice on its first line. A planned write over an existing file that is not -owned marks the change `foreign`; add, update apply and combined apply stop with -`InstructionError.unownedTargets` unless `replace` is set. A locked target that +A file is owned when `Instructions.isOwned` finds it blank or finds the notice +on its first line; a lock entry alone does not make a file owned. A planned +write over an existing file that is not owned marks the change `foreign`; add, +update apply, combined apply, remove and install stop with +`InstructionError.unownedTargets` unless `replace` is set, which install does +not offer. A locked target that no longer receives sections is deleted while its bytes equal the locked rendering and kept otherwise. Unit targets lock `headingOffset: 0`, `created: false` and the rendered file's hash as `blockHash`. @@ -105,7 +112,10 @@ also suffices. Otherwise, when the root `AGENTS.md` is a target, the first existing file in `CLAUDE.md`, `.claude/CLAUDE.md`, `CLAUDE.local.md` order receives a managed import block: `@AGENTS.md` or `@../AGENTS.md`, relative to its containing file. No project Claude file means automatic forwarding. -Ancestor files are reported and never modified. +Ancestor files are reported and never modified. Claude Code reads a nested +`AGENTS.md` only while no Claude file exists at the project root or in that +directory, unless that directory's Claude file imports it; nested Claude files +are not modified, and doctor reports one that hides a generated target. ## Operations and Mutation Contract @@ -123,9 +133,14 @@ Ancestor files are reported and never modified. | `doctor(projectRoots:environment:codexConfiguration:)` | Audit explicit project roots without writing | | `export(projectRoots:environment:)` | Map the user scope's and each root's locked targets to their sections without writing | -An `agents` argument sets the complete instruction recipient list. Removing -names accepts `alias:name` references or unambiguous bare names and removes -those sections from prompts as well. Empty prompts are removed. Other source +An `agents` argument sets the complete instruction recipient list. A name to +remove that equals a declared reference, such as an own file's bare name or +`alias:name`, selects that reference; another bare name must match exactly one +source reference. Removal also removes those sections from prompts. +Export maps a user target to every locked section from the lock alone. A +project section's placement needs its `paths`, read from the working tree or +the cache without fetching; a section whose content is unavailable is listed as +unplaced. Empty prompts are removed. Other source declarations and skill records remain available to their owners. Planning validates required content before applying. Reports include old and @@ -170,8 +185,9 @@ publish materializations, declaration, lock or targets. Doctor and export read remote ref advertisements at most and do not fetch objects or create files, including in projects with no state directory. -Install renders the locked sections, verifies every rendering against its -locked hash before replacement, and restores drifted files. Lost-lock update +Install renders the locked sections into the locked targets and Claude import +files, verifies every rendering against its locked hash before replacement, and +restores drifted files; it never recomputes forwarding or placement. Lost-lock update reports the comparison; apply keeps identical files, replaces differing generated files, takes over others only with `replace`, and records targets as `created: false`. Without a lock entry a file is never deleted. @@ -192,9 +208,9 @@ ChatGPT. ## Diagnostics -Doctor reports missing targets, drifted targets, files in target locations that -agents did not generate, own files changed since the lock, links in the locked -renderings that no longer resolve, invalid targets, missing locks, duplicate +Doctor reports missing targets, drifted targets, locked targets that agents +does not own, own files changed since the lock (including those only prompts +use), links in the locked renderings that no longer resolve, invalid targets, missing locks, duplicate source-qualified sections across scopes, Claude forwarding and ancestor problems, and uncommitted selected local source paths. Git status uses `--no-optional-locks` to avoid index refresh writes. File and ChatGPT prompt pins diff --git a/Documentation/Architecture/Package.md b/Documentation/Architecture/Package.md index 36539c0..b05e09f 100644 --- a/Documentation/Architecture/Package.md +++ b/Documentation/Architecture/Package.md @@ -275,11 +275,11 @@ state, transactions, concurrency, requirements, mirrors, snapshots, hashes and agent paths. Skill tests cover discovery, artifact formats and the full declared lifecycle, including public consumer calls and failed-operation preservation. Fixtures create isolated homes and explicit Git initial branches and remove -their temporary roots. Instruction tests cover source validation, managed-block -assembly and removal, byte preservation, drift, Claude forwarding, and ChatGPT -rendering through public APIs with in-memory fixtures. Lifecycle tests cover -pinned sources, physical targets, transactional writes, conflict stops, lost -locks, prompts, deletion ownership and read-only multi-root audits. +their temporary roots. Instruction tests cover the instructions file format, +generation, link checks, Claude forwarding and ChatGPT rendering through public +APIs with in-memory fixtures. Lifecycle tests cover pinned sources, own +instructions, nested and physical targets, transactional writes, ownership +stops, lost locks, prompts, deletion, export and read-only multi-root audits. [State and cache](State.md) describes persisted data and lifecycle invariants. `../Proposals/` holds design work; `../Decisions/`, `../Migrations/` and diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 94c3967..568c24a 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -8,7 +8,8 @@ | User | `~/.agents/agents.json` | `~/.agents/agents.resolved` | `~/.agents/agents.watch` | `~/.agents/cache/` | User paths are relative to `RuntimeEnvironment.homeDirectory`. State files belong -to their scope and are local state. `agents.watch` stores subscription baselines +to their scope. A project may commit its declaration and lock; the cache, the +writer lock and the journal stay local. `agents.watch` stores subscription baselines independently of installed pins; [Watch](Watch.md) describes the operations. ## Declaration @@ -18,7 +19,10 @@ independently of installed pins; [Watch](Watch.md) describes the operations. location, an optional requirement, and an optional search `path`. A source added by location keeps the alias already declaring it, or receives its location's last path component; while another source holds that name, preceding components are -prefixed (`anthropics-skills`), then a number is appended. +prefixed (`anthropics-skills`), then a number is appended. `sources` may be +omitted. An operation writes `agents.json`, in normalized form, only when it +changes the declaration's content, so a hand-written declaration keeps its +formatting otherwise. ```json { @@ -54,7 +58,8 @@ Source IDs are Git `host[:port]/path` with a lowercase host and without user, scheme or `.git`; `local:` plus an absolute path; or a well-known URL retaining its scheme. Declaring two aliases for one normalized ID is an error. -`instructions` holds recipients, ordered `source:name` section references, and +`instructions` holds recipients, ordered section references (`alias:name`, or a +bare name for the project's own instructions), and named `chatgpt` prompts with ordered sections and optional relative `append` paths. `watch` is a unique alias array. Skill operations preserve both fields and existing watch-state bytes. diff --git a/Documentation/Proposals/AgentInstructions.md b/Documentation/Proposals/AgentInstructions.md index 8ac8aa6..2d67e00 100644 --- a/Documentation/Proposals/AgentInstructions.md +++ b/Documentation/Proposals/AgentInstructions.md @@ -442,8 +442,8 @@ target or checked-out revision. They may fetch new objects into a source mirror. `doctor` reports missing installs, drifted skill copies, missing or drifted -targets, existing files in target locations that agents did not generate, own -instructions changed since the lock, invalid instructions files and links, +targets, locked targets that agents did not generate, own instructions changed +since the lock, links in the locked renderings that no longer resolve, sources with newer matching versions, local sources with uncommitted changes in selected paths, sections installed at both scopes, Claude Code forwarding problems, and a Codex `AGENTS.override.md` that hides a managed `AGENTS.md`. @@ -491,7 +491,11 @@ above it. When `claude-code` is a target in project scope: formatted tokens, and quoted tokens do not count; - a `CLAUDE.md`, `.claude/CLAUDE.md` or `CLAUDE.local.md` in a directory above the project root is outside the project; `doctor` warns about it and nothing - is written. User-level and managed-policy files do not count. + is written. User-level and managed-policy files do not count; +- Claude Code reads a nested `AGENTS.md` only while no such file exists at the + project root or in that directory, unless the directory's own Claude file + imports it. Nested Claude files are not written; `doctor` reports one, or a + root Claude file, that keeps a generated nested `AGENTS.md` from loading. ## Writing Targets @@ -529,10 +533,10 @@ Read `README.md` first. 4. The assembled target is parsed before it is written. Each section's first heading must remain a document-level heading, and its links must satisfy the rules under Sources; otherwise nothing is written. -5. A file is owned when the lock records it as a target or its first line is - the notice. Writing over an existing file that is not owned requires - `--replace`, after its difference is shown; otherwise `add` and - `update --apply` stop and name the file. +5. A file is owned when it is blank or its first line is the notice; a lock + entry alone does not make it owned. Writing over an existing file that is + not owned requires `--replace`, after its difference is shown; otherwise + `add`, `update --apply`, `remove` and `install` stop and name the file. 6. A section's `hash` covers the instructions file's bytes. `blockHash` covers the rendered target with LF endings. Any difference between a target and its locked rendering is drift: `doctor` reports it, `install` restores the diff --git a/README.md b/README.md index 928fe51..689ec6a 100644 --- a/README.md +++ b/README.md @@ -214,7 +214,7 @@ by bare name. `InstructionOperations` generates whole target files from them: locked rendering. - `renderChatGPT(prompt:...)` renders locked sections plus a custom append file. Prompts live in `instructions.chatgpt`. -- `doctor(...)` checks missing, drifted and hand-written targets, changed own +- `doctor(...)` checks missing, drifted and unowned locked targets, changed own files, links, scope duplication, Claude forwarding, Codex overrides and the project size budget, newer matching source revisions and uncommitted sources. Its `projectRoots` overload audits explicit projects without writing. diff --git a/Sources/AgentsCore/Declaration.swift b/Sources/AgentsCore/Declaration.swift index 359ea00..ee78408 100644 --- a/Sources/AgentsCore/Declaration.swift +++ b/Sources/AgentsCore/Declaration.swift @@ -198,6 +198,19 @@ public struct Declaration: Codable, Equatable, Sendable { self.watch = watch } + /// A missing `sources` key means no declared sources, as in a project that selects only its + /// own instructions. + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + agents = try container.decodeIfPresent([AgentID].self, forKey: .agents) + sources = + try container.decodeIfPresent([String: SourceDeclaration].self, forKey: .sources) ?? [:] + skills = try container.decodeIfPresent([String: SkillDeclaration].self, forKey: .skills) + instructions = try container.decodeIfPresent( + InstructionsDeclaration.self, forKey: .instructions) + watch = try container.decodeIfPresent([String].self, forKey: .watch) + } + public var defaultAgents: [AgentID] { agents ?? [.codex, .claudeCode] } public func validate(environment: RuntimeEnvironment) throws { diff --git a/Sources/AgentsCore/InstructionLocations.swift b/Sources/AgentsCore/InstructionLocations.swift index 63e3f91..4efb755 100644 --- a/Sources/AgentsCore/InstructionLocations.swift +++ b/Sources/AgentsCore/InstructionLocations.swift @@ -7,7 +7,7 @@ package enum InstructionLocations { ] /// Whether a project-relative path is a root instruction file, or a generated `AGENTS.md` or - /// `GEMINI.md` in a project directory outside `.git` and `.agent`. + /// `GEMINI.md` in a project directory outside any `.git` and the top-level `.agent`. package static func isProjectTarget(_ relative: String) -> Bool { if projectPaths.contains(relative) { return true } let parts = relative.split(separator: "/", omittingEmptySubsequences: false) @@ -15,8 +15,9 @@ package enum InstructionLocations { else { return false } let directories = parts.dropLast() return directories.allSatisfy { - !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("\\") && !$0.contains("\0") - } && directories.first != ".git" && directories.first != ".agent" + !$0.isEmpty && $0 != "." && $0 != ".." && $0 != ".git" && !$0.contains("\\") + && !$0.contains("\0") + } && directories.first != ".agent" } package static func file( diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index 9f3f7bd..7ebb928 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -61,8 +61,7 @@ public struct StateStore: Sendable { _ = try readDeclaration() _ = try readResolved() let transaction = FileTransaction(store: self) - try transaction.replace( - declarationURL, content: nil, data: Self.encode(declaration.normalized)) + try stageDeclaration(declaration, in: transaction) try transaction.replace(resolvedURL, content: nil, data: Self.encode(resolved.normalized)) if let watch { try transaction.replace(watchURL, content: nil, data: Self.encode(watch)) @@ -71,6 +70,15 @@ public struct StateStore: Sendable { } } + /// Stages the declaration only when its content differs from the file's, so a declaration + /// whose content an operation leaves unchanged keeps its author's formatting. + package func stageDeclaration(_ declaration: Declaration, in transaction: FileTransaction) throws + { + let current: Declaration? = try load(declarationURL) + guard current?.normalized != declaration.normalized else { return } + try transaction.replace(declarationURL, content: nil, data: Self.encode(declaration.normalized)) + } + package func withLock( createIfMissing: Bool = true, checkpoint: @escaping (String) throws -> Void = { _ in }, outcome: TransactionOutcome? = nil, diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index 3a1f72f..d7221fe 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -170,8 +170,7 @@ public struct WatchOperations: Sendable { try watch.validate() let transaction = FileTransaction(store: store, checkpoint: checkpoint) if let declaration { - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(declaration.normalized)) + try store.stageDeclaration(declaration, in: transaction) } try transaction.replace(store.watchURL, content: nil, data: StateStore.encode(watch)) try SourceCache(store: store).prune(referencedBy: lock, watch: watch, transaction: transaction) diff --git a/Sources/AgentsInstructions/InstructionDoctor.swift b/Sources/AgentsInstructions/InstructionDoctor.swift index b0927b0..4f9114a 100644 --- a/Sources/AgentsInstructions/InstructionDoctor.swift +++ b/Sources/AgentsInstructions/InstructionDoctor.swift @@ -51,7 +51,11 @@ extension InstructionOperations { var unchanged = true if scope == .project { let project = environment.projectDirectory.resolvingSymlinksInPath() - for record in lock.instructions.sections where record.source == InstructionSources.own { + let records = + lock.instructions.sections + lock.instructions.chatgpt.values.flatMap(\.sections) + var seen = Set() + for record in records + where record.source == InstructionSources.own && seen.insert(record.path).inserted { let file = project.appendingPathComponent(record.path) let current = try? Data(contentsOf: file) if current.map(Instructions.hash) != record.hash { @@ -82,7 +86,9 @@ extension InstructionOperations { } continue } - if let bytes, Instructions.hash(bytes) != target.blockHash { + if let bytes, !Instructions.isOwned(bytes) { + report(.foreignTarget, "Target file was not generated by agents.", file) + } else if let bytes, Instructions.hash(bytes) != target.blockHash { report(.drift, "Generated instructions differ from their lock.", file) } else if bytes == nil { report(.missingTarget, "Generated instructions file is missing.", file) @@ -113,15 +119,38 @@ extension InstructionOperations { } let agents = Set(lock.instructions.targets.values.flatMap(\.agents)) .union(declaration.instructions?.agents ?? declaration.defaultAgents) - if scope == .project, agents.contains(.claudeCode) { + let claudeTargets = lock.instructions.targets.filter { + $0.value.import == nil && $0.value.agents.contains(.claudeCode) + }.keys.sorted() + if scope == .project, !claudeTargets.isEmpty { do { - if case .needsImport(let path) = try ClaudeForwarding.classify( - InstructionTargets(store: store).claudeFiles()) + let targets = InstructionTargets(store: store) + let rootFiles = try targets.claudeFiles() + if claudeTargets.contains("AGENTS.md"), + case .needsImport(let path) = try ClaudeForwarding.classify(rootFiles) { report( .claudeForwarding, "Claude file does not forward to the project's AGENTS.md.", environment.projectDirectory.appendingPathComponent(path.rawValue)) } + // Claude Code reads a nested AGENTS.md only while no Claude file exists at the project + // root or in its own directory, unless that directory's Claude file imports it. + for key in claudeTargets where key != "AGENTS.md" { + let directory = (key as NSString).deletingLastPathComponent + let folder = environment.projectDirectory.appendingPathComponent(directory) + let files = try targets.claudeFiles(in: folder) + if case .needsImport(let path) = try ClaudeForwarding.classify(files) { + report( + .claudeForwarding, + "Claude Code reads this file instead of \(key); import AGENTS.md from it.", + folder.appendingPathComponent(path.rawValue)) + } else if files.isEmpty, let hiding = rootFiles.first { + report( + .claudeForwarding, + "Claude Code does not read \(key) while \(hiding.path.rawValue) exists at the project root; add a Claude file in \(directory) that imports AGENTS.md.", + folder.appendingPathComponent("AGENTS.md")) + } + } } catch { report(.claudeForwarding, "Cannot inspect Claude forwarding: \(error)") } let userClaude = InstructionLocations.file( for: .claudeCode, scope: .user, environment: environment)?.resolvingSymlinksInPath() diff --git a/Sources/AgentsInstructions/InstructionExport.swift b/Sources/AgentsInstructions/InstructionExport.swift index 0097b29..1d52361 100644 --- a/Sources/AgentsInstructions/InstructionExport.swift +++ b/Sources/AgentsInstructions/InstructionExport.swift @@ -24,7 +24,8 @@ public struct InstructionMapping: Sendable, Equatable { public let root: URL public let status: Status public let targets: [Target] - /// Locked sections whose placement cannot be read, such as an own file changed since the lock. + /// Project sections whose placement needs content that is not available without fetching: an + /// own file changed since the lock, or a source section missing from the cache. public let unplaced: [LockedSection] public let prompts: [String: [LockedSection]] } @@ -66,12 +67,14 @@ extension InstructionOperations { let sources = InstructionSources(store: store) var directories: [String: String] = [:] var unplaced: [LockedSection] = [] + // User targets receive every section, so their placement needs no content. for record in lock.instructions.sections { - if let unit = try? sources.restore([record], sources: lock.sources, cachedOnly: true) - .first - { - directories[InstructionSources.identity(record)] = - scope == .project ? unit.section.directory : "" + if scope == .user { + directories[InstructionSources.identity(record)] = "" + } else if let unit = try? sources.restore( + [record], sources: lock.sources, cachedOnly: true + ).first { + directories[InstructionSources.identity(record)] = unit.section.directory } else { unplaced.append(record) } diff --git a/Sources/AgentsInstructions/InstructionLifecycleModels.swift b/Sources/AgentsInstructions/InstructionLifecycleModels.swift index 744a6be..3d97b97 100644 --- a/Sources/AgentsInstructions/InstructionLifecycleModels.swift +++ b/Sources/AgentsInstructions/InstructionLifecycleModels.swift @@ -97,6 +97,7 @@ public struct InstructionDiagnostic: Sendable, Equatable { public enum Kind: String, Sendable { case missingTarget case drift + case foreignTarget case ownChanged case invalidLink case invalidTarget diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index e15e8ae..292b866 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -164,8 +164,7 @@ public enum InstructionOperations { try plan.validate() let transaction = FileTransaction(store: store) try plan.stage(transaction: transaction) - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(declaration.normalized)) + try store.stageDeclaration(declaration, in: transaction) try transaction.replace( store.resolvedURL, content: nil, data: StateStore.encode(plan.next.normalized)) try SourceCache(store: store).prune(referencedBy: plan.next, transaction: transaction) @@ -209,13 +208,15 @@ public enum InstructionOperations { sections: [], targets: targets.changes, changedPrompts: [], lockMissing: !FileManager.default.fileExists(atPath: store.resolvedURL.path), hasChanges: targets.changes.contains(where: \.changed)) + try requireOwnership(report) try apply( declaration: declaration, next: lock, report: report, sources: sources, writeState: false) return report } } - /// Removes selected identities from file targets and named prompts. Bare names must be unambiguous. + /// Removes selected references from file targets and named prompts. A name equal to a declared + /// reference selects it; another bare name must match exactly one source reference. @discardableResult public static func remove( names: [String], scope: InstallScope = .project, agents: [AgentID]? = nil, @@ -230,9 +231,12 @@ public enum InstructionOperations { instructions.sections + (instructions.chatgpt ?? [:]).values.flatMap(\.sections)) var removed = Set() for name in names { - let matches = references.filter { - $0 == name || $0.split(separator: ":").last.map(String.init) == name - } + // A declared reference matches itself, such as an own file's bare name; otherwise a bare + // name matches a source reference with that name. + let exact = references.filter { $0 == name } + let matches = + exact.isEmpty + ? references.filter { InstructionSources.split($0)?.name == name } : exact guard matches.count == 1, let reference = matches.first else { throw CoreError.notFound("instruction name is missing or ambiguous: \(name)") } @@ -424,8 +428,7 @@ public enum InstructionOperations { if change.changed { try transaction.replace(change.url, content: nil, data: change.after) } } if writeState { - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(declaration.normalized)) + try store.stageDeclaration(declaration, in: transaction) try transaction.replace( store.resolvedURL, content: nil, data: StateStore.encode(next.normalized)) } diff --git a/Sources/AgentsInstructions/InstructionSources.swift b/Sources/AgentsInstructions/InstructionSources.swift index 31d6906..66fbcc6 100644 --- a/Sources/AgentsInstructions/InstructionSources.swift +++ b/Sources/AgentsInstructions/InstructionSources.swift @@ -88,15 +88,30 @@ final class InstructionSources { return units } + /// One of the project's own instructions, read from the working tree as it is. Other files in + /// the container are not read, so an unfinished draft affects only operations that list them. + func own(named name: String) throws -> InstructionUnit { + guard store.scope == .project else { + throw CoreError.invalidState("own instructions exist only in project scope") + } + let project = store.environment.projectDirectory.resolvingSymlinksInPath() + let path = Self.ownContainer + "/" + name + ".md" + let file = project.appendingPathComponent(path) + guard Declaration.isInstructionName(name), FileManager.default.fileExists(atPath: file.path) + else { throw CoreError.notFound("own instructions file: \(name)") } + try Self.requireNoLinks(file, below: project) + let section = try Instructions.validateSource(Data(contentsOf: file), id: name) + return InstructionUnit( + record: LockedSection(name: name, source: Self.own, path: path, hash: section.hash), + section: section) + } + func resolve( references: [String], declaration: Declaration, lock: inout ResolvedState ) throws -> [InstructionUnit] { try references.map { reference in guard let (alias, name) = Self.split(reference) else { - guard let unit = try own().first(where: { $0.record.name == reference }) else { - throw CoreError.notFound("own instructions file: \(reference)") - } - return unit + return try own(named: reference) } guard let source = declaration.sources[alias] else { throw CoreError.invalidState("invalid instruction reference: \(reference)") @@ -116,7 +131,7 @@ final class InstructionSources { { try records.map { record in if record.source == Self.own { - guard let unit = try own().first(where: { $0.record.path == record.path }), + guard let unit = try? own(named: record.name), unit.record.path == record.path, unit.record.hash == record.hash else { throw InstructionError.ownChanged(name: record.name) } return unit @@ -184,10 +199,25 @@ final class InstructionSources { } } - /// The `.md` files below a container, by name. Symbolic links and invalid names are errors. + /// Rejects a symbolic link at `url` or at any directory between `tree` and it. + private static func requireNoLinks(_ url: URL, below tree: URL) throws { + var cursor = tree + for component in PathSafety.relativePath(url.path, to: tree.path).split(separator: "/") { + cursor.appendPathComponent(String(component)) + if (try? FileManager.default.destinationOfSymbolicLink(atPath: cursor.path)) != nil { + throw CoreError.invalidSource( + "instructions containers hold no symbolic links: \(PathSafety.relativePath(cursor.path, to: tree.path))" + ) + } + } + } + + /// The `.md` files below a container, by name, except the target names `AGENTS.md` and + /// `GEMINI.md`, which a project may generate there. Symbolic links and invalid names are errors. private static func files(in directory: URL, tree: URL) throws -> [(String, URL)] { guard FileManager.default.fileExists(atPath: directory.path) else { return [] } try contained(directory, in: tree) + try requireNoLinks(directory, below: tree) var result: [(String, URL)] = [] func walk(_ directory: URL, prefix: String) throws { let keys: [URLResourceKey] = [.isSymbolicLinkKey, .isDirectoryKey, .isRegularFileKey] @@ -202,7 +232,9 @@ final class InstructionSources { } if values.isDirectory == true { try walk(entry, prefix: prefix + component + "/") - } else if values.isRegularFile == true, entry.pathExtension == "md" { + } else if values.isRegularFile == true, entry.pathExtension == "md", + !["AGENTS.md", "GEMINI.md"].contains(component) + { let name = prefix + entry.deletingPathExtension().lastPathComponent guard Declaration.isInstructionName(name) else { throw CoreError.invalidSource( diff --git a/Sources/AgentsInstructions/InstructionTargets.swift b/Sources/AgentsInstructions/InstructionTargets.swift index bb0d33e..8a58bf1 100644 --- a/Sources/AgentsInstructions/InstructionTargets.swift +++ b/Sources/AgentsInstructions/InstructionTargets.swift @@ -5,8 +5,8 @@ struct InstructionTargets { let store: StateStore /// Plans every generated target from `sections` in declared order, the Claude import, and the - /// removal of targets that no longer receive sections. `restoring` keeps the locked recipients - /// and requires each rendering to match its locked hash. + /// removal of targets that no longer receive sections. `restoring` keeps the locked targets, + /// recipients and Claude imports, and requires each rendering to match its locked hash. func plan( sections: [InstructionSection], agents: [AgentID], previous: LockedInstructions, restoring: Bool = false @@ -26,6 +26,7 @@ struct InstructionTargets { groups[directory, default: []].append(section) } for directory in order { + if !directory.isEmpty { try validateNested(directory) } let text = try Instructions.render(groups[directory]!) for agent in recipients.sorted(by: { $0.rawValue < $1.rawValue }) { guard let file = try location(for: agent, directory: directory) else { continue } @@ -41,8 +42,8 @@ struct InstructionTargets { } } } - if store.scope == .project, recipients.contains(.claudeCode), targets["AGENTS.md"] != nil, - let path = try forwardingPath() + if !restoring, store.scope == .project, recipients.contains(.claudeCode), + targets["AGENTS.md"] != nil, let path = try forwardingPath() { let file = store.environment.projectDirectory.appendingPathComponent(path.rawValue) let key = InstructionLocations.key(for: InstructionLocations.physical(file), store: store) @@ -54,6 +55,12 @@ struct InstructionTargets { created: false) } } + if restoring { + guard + Set(targets.keys) == Set(previous.targets.filter { $0.value.import == nil }.keys) + else { throw InstructionError.invalidLockedBlock } + for (key, target) in previous.targets where target.import != nil { targets[key] = target } + } var changes: [InstructionTargetChange] = [] var problems: [InstructionLinkProblem] = [] for key in Set(previous.targets.keys).union(targets.keys).sorted() { @@ -75,8 +82,7 @@ struct InstructionTargets { throw CoreError.notFound("the directory of instruction target \(key)") } after = Data(text.utf8) - foreign = - before != nil && before != after && old == nil && !Instructions.isGenerated(before!) + foreign = before.map { $0 != after && !Instructions.isOwned($0) } ?? false if restoring, targets[key]?.blockHash != old?.blockHash { throw InstructionError.invalidLockedBlock } @@ -122,6 +128,25 @@ struct InstructionTargets { return InstructionLocations.physical(file) } + /// A nested target's directory is a real directory of this checkout: no component is a symbolic + /// link or `.git`, and none holds another repository or worktree. + private func validateNested(_ directory: String) throws { + var cursor = store.environment.projectDirectory.resolvingSymlinksInPath() + for component in directory.split(separator: "/").map(String.init) { + cursor.appendPathComponent(component) + if component == ".git" + || (try? FileManager.default.destinationOfSymbolicLink(atPath: cursor.path)) != nil + { + throw CoreError.unsafePath( + "an instruction target directory cannot be a symbolic link or Git metadata: \(directory)") + } + if FileManager.default.fileExists(atPath: cursor.appendingPathComponent(".git").path) { + throw CoreError.unsafePath( + "an instruction target directory cannot be inside another repository: \(directory)") + } + } + } + private func directoryExists(of file: URL) -> Bool { var isDirectory: ObjCBool = false return FileManager.default.fileExists( @@ -148,7 +173,9 @@ struct InstructionTargets { /// the checkout being written. User targets belong to no checkout, so every local link fails. func linkProblems(in text: String, file: URL, key: String) -> [InstructionLinkProblem] { var problems: [InstructionLinkProblem] = [] - let root = store.environment.projectDirectory.resolvingSymlinksInPath() + let root = + Self.realPath(store.environment.projectDirectory.path) + ?? store.environment.projectDirectory.resolvingSymlinksInPath() for link in Instructions.localLinks(in: text) { func problem(_ reason: String) { problems.append( @@ -166,11 +193,18 @@ struct InstructionTargets { problem("points to a local file; user instructions cannot link to local files") continue } - let resolved = - (path.hasPrefix("/") - ? URL(fileURLWithPath: path) - : file.deletingLastPathComponent().appendingPathComponent(path)) - .standardizedFileURL.resolvingSymlinksInPath() + let destination = + path.hasPrefix("/") ? path : file.deletingLastPathComponent().path + "/" + path + guard let resolved = Self.realPath(destination) else { + let lexical = URL(fileURLWithPath: destination).standardizedFileURL + let project = store.environment.projectDirectory + let inside = [root, project.standardizedFileURL, project.resolvingSymlinksInPath()] + .contains { PathSafety.isContained(lexical, in: $0) } + problem( + inside + ? "does not resolve to an existing file" : "points outside the checkout being written") + continue + } guard PathSafety.isContained(resolved, in: root), resolved != root else { problem("points outside the checkout being written") continue @@ -194,11 +228,20 @@ struct InstructionTargets { return problems } - func claudeFiles() throws -> [ClaudeInstructionFile] { - let agents = store.environment.projectDirectory.appendingPathComponent("AGENTS.md") - .resolvingSymlinksInPath() + /// The path with each symbolic link resolved before a following `..`, as the kernel resolves it + /// for a reader, or nil when it does not exist. + private static func realPath(_ path: String) -> URL? { + guard let real = realpath(path, nil) else { return nil } + defer { free(real) } + return URL(fileURLWithPath: String(cString: real)) + } + + /// The Claude files in `directory`, the project root by default, beside its `AGENTS.md`. + func claudeFiles(in directory: URL? = nil) throws -> [ClaudeInstructionFile] { + let directory = directory ?? store.environment.projectDirectory + let agents = directory.appendingPathComponent("AGENTS.md").resolvingSymlinksInPath() return try ClaudeInstructionPath.allCases.compactMap { path in - let file = store.environment.projectDirectory.appendingPathComponent(path.rawValue) + let file = directory.appendingPathComponent(path.rawValue) let link = try? FileManager.default.destinationOfSymbolicLink(atPath: file.path) guard link != nil || FileManager.default.fileExists(atPath: file.path) else { return nil } if let link, diff --git a/Sources/AgentsInstructions/Instructions.swift b/Sources/AgentsInstructions/Instructions.swift index 1d86d9b..4206959 100644 --- a/Sources/AgentsInstructions/Instructions.swift +++ b/Sources/AgentsInstructions/Instructions.swift @@ -32,13 +32,13 @@ public enum Instructions { while body.first.map(isBlank) == true { body.removeFirst() } while body.last.map(isBlank) == true { body.removeLast() } let document = MarkdownDocument(body.joined(separator: "\n")) - guard let first = document.topLevelHeadings.first, first.isATX, first.lines.lowerBound == 0 + guard let first = document.topLevelHeadings.first, first.isATX, first.line == 0 else { throw invalid("the body must start with an ATX heading.") } guard document.headings.allSatisfy(\.isATX) else { throw invalid("Setext headings are not allowed; use ATX headings.") } guard - document.headings.allSatisfy({ $0.lines.lowerBound == 0 || $0.level > first.level }) + document.headings.allSatisfy({ $0.line == 0 || $0.level > first.level }) else { throw invalid("every heading after the first must be deeper than the first.") } guard !document.endsInCode else { throw invalid("the body ends inside a code block.") } guard !document.endsInHTML else { throw invalid("the body ends inside an HTML block.") } @@ -89,7 +89,7 @@ public enum Instructions { for heading in expected { guard document.topLevelHeadings.contains(where: { - $0.lines.lowerBound == heading.line && $0.level == heading.level + $0.line == heading.line && $0.level == heading.level }) else { throw InstructionError.invalidAssembly } } @@ -103,6 +103,12 @@ public enum Instructions { return MarkdownLine.parse(text).first?.text == notice } + /// Whether agents may write over a file without `replace`: it is blank, or its first line is the + /// notice. + public static func isOwned(_ bytes: Data) -> Bool { + isGenerated(bytes) || String(decoding: bytes, as: UTF8.self).allSatisfy(\.isWhitespace) + } + /// Sections render as in targets, without the notice. Custom text follows after one blank line. public static func renderChatGPT( sections: [InstructionSection], customContent: Data? = nil diff --git a/Sources/AgentsInstructions/MarkdownDocument.swift b/Sources/AgentsInstructions/MarkdownDocument.swift index 43aa9f8..83a7edb 100644 --- a/Sources/AgentsInstructions/MarkdownDocument.swift +++ b/Sources/AgentsInstructions/MarkdownDocument.swift @@ -36,7 +36,8 @@ struct MarkdownLine: Sendable, Equatable { struct MarkdownHeading: Sendable, Equatable { let level: Int let text: String - let lines: Range + /// The line where CommonMark starts the heading. + let line: Int /// UTF-8 offset of the ATX opening run, including container prefixes; nil for Setext. let openingOffset: Int? var isATX: Bool { openingOffset != nil } @@ -72,27 +73,10 @@ struct MarkdownDocument: Sendable, Equatable { var pending: [(Markup, Bool)] = [(parsed, false)] while let (node, topLevel) = pending.popLast() { if let range = node.range, let heading = node as? Heading { - var first = range.lowerBound.line - 1 - let opening = Self.atxOpening(in: lines[first].text, inContainer: !topLevel) - let end: Int - if opening != nil { - end = first + 1 - } else if topLevel { - let contentStart = firstContentLine( - afterDefinitionsAt: first, before: min(range.upperBound.line, lines.count)) - first = contentStart - // A Setext range can extend into the following block. Verify the physical underline. - end = - ((first + 1).. Bool { - let bytes = Array(line.utf8) - let indentation = bytes.prefix(while: { $0 == 32 }).count - guard indentation <= 3 else { return false } - let marker: UInt8 = level == 1 ? 61 : 45 - let run = bytes.dropFirst(indentation).prefix(while: { $0 == marker }).count - return run > 0 && bytes.dropFirst(indentation + run).allSatisfy { $0 == 32 || $0 == 9 } - } - - private func firstContentLine(afterDefinitionsAt first: Int, before end: Int) -> Int { - guard lines[first].text.trimmingCharacters(in: .whitespaces).hasPrefix("[") else { - return first - } - // Complete definition-only prefixes produce no AST blocks. Testing physical prefixes also - // handles destinations and titles on later lines, without relying on logical inline ranges. - var prefix = "" - var contentStart = first - for line in first.. Markup { var node = document while node is Document || node is BlockQuote || node is ListItem || node is ListItemContainer { diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index b65d97a..24ba425 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -221,8 +221,7 @@ final class SkillLifecycle { previous: previous, next: next, prepared: prepared, retained: retained, names: names, transaction: transaction) if writeState { - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(declaration.normalized)) + try store.stageDeclaration(declaration, in: transaction) try transaction.replace( store.resolvedURL, content: nil, data: StateStore.encode(next.normalized)) } diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 5ad6c5f..552d2d0 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -159,8 +159,7 @@ public enum SkillOperations { try plan.validate() let transaction = FileTransaction(store: store) try plan.stage(retained: retained, transaction: transaction) - try transaction.replace( - store.declarationURL, content: nil, data: StateStore.encode(declaration.normalized)) + try store.stageDeclaration(declaration, in: transaction) try transaction.replace( store.resolvedURL, content: nil, data: StateStore.encode(plan.next.normalized)) try SourceCache(store: store).prune(referencedBy: plan.next, transaction: transaction) diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 275d0a5..775f159 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -80,10 +80,7 @@ final class UpdatePlan { let transaction = FileTransaction(store: store, outcome: outcome, checkpoint: checkpoint) try skills.stage(retained: retained, transaction: transaction) try instructions.stage(transaction: transaction) - let declarationBytes = try StateStore.encode(declaration.normalized) - if try store.existingData(store.declarationURL) != declarationBytes { - try transaction.replace(store.declarationURL, content: nil, data: declarationBytes) - } + try store.stageDeclaration(declaration, in: transaction) let resolvedBytes = try StateStore.encode(next.normalized) if try store.existingData(store.resolvedURL) != resolvedBytes { try transaction.replace(store.resolvedURL, content: nil, data: resolvedBytes) diff --git a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift index 3e0f971..b20303f 100644 --- a/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/DoctorLifecycleTests.swift @@ -118,7 +118,7 @@ struct InstructionDoctorTests { #expect(!report.diagnostics.contains { $0.kind == .invalidConfiguration }) } - @Test func doctorReportsEveryDifferenceFromALockedTargetAsDrift() throws { + @Test func doctorReportsForeignAndDriftedTargetsWithoutWriting() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() @@ -127,7 +127,7 @@ struct InstructionDoctorTests { try fixture.write("# rules\n\nOriginal\n", to: file) #expect( try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { - $0.kind == .drift && $0.path == file + $0.kind == .foreignTarget && $0.path == file }) try fixture.write(generated(["# rules\n\nCustom"]), to: file) let report = try InstructionOperations.doctor(environment: fixture.environment) diff --git a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift index cfa1e57..2b8cba6 100644 --- a/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleSafetyTests.swift @@ -56,7 +56,8 @@ struct InstructionLifecycleSafetyTests { _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) #expect(try fixture.bytes() == locked) try fixture.write( - "## rules\n\nEdited.\n", to: fixture.project.appendingPathComponent("AGENTS.md")) + Instructions.notice + "\n\n## rules\n\nEdited.\n", + to: fixture.project.appendingPathComponent("AGENTS.md")) let report = try InstructionOperations.installResolvedReport(environment: fixture.environment) #expect(report.targets.first?.drift == .drifted) #expect(try fixture.bytes() == locked) diff --git a/Tests/AgentsInstructionsTests/LifecycleTests.swift b/Tests/AgentsInstructionsTests/LifecycleTests.swift index 80817f1..b901843 100644 --- a/Tests/AgentsInstructionsTests/LifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/LifecycleTests.swift @@ -138,7 +138,13 @@ struct InstructionLifecycleTests { _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) #expect(try fixture.text() == generated(["# two\n\nOriginal", "# one\n\nUpstream"])) let applied = try fixture.bytes() - try fixture.write("Drift\n", to: fixture.project.appendingPathComponent("AGENTS.md")) + let file = fixture.project.appendingPathComponent("AGENTS.md") + try fixture.write("Drift\n", to: file) + #expect(throws: InstructionError.unownedTargets(["AGENTS.md"])) { + try InstructionOperations.installResolvedReport(environment: fixture.environment) + } + #expect(try fixture.text() == "Drift\n") + try fixture.write("\n", to: file) _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) #expect(try fixture.bytes() == applied) } @@ -253,7 +259,7 @@ struct InstructionLifecycleTests { } } - @Test func lostLockIsReportedAndIdenticalBlocksAreAdoptedWithoutDeletionOwnership() throws { + @Test func lostLockIsReportedAndUpdateRelocksIdenticalTargets() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() diff --git a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift new file mode 100644 index 0000000..55c6e54 --- /dev/null +++ b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift @@ -0,0 +1,197 @@ +import AgentsCore +import AgentsInstructions +import Foundation +import Testing + +@Suite("Ownership, placement and restore safety") +struct OwnershipAndPlacementTests { + @Test func lockedTargetWithoutTheNoticeNeedsReplace() throws { + let fixture = try InstructionFixture() + try fixture.section("rules") + try fixture.commit() + try fixture.add() + let file = fixture.project.appendingPathComponent("AGENTS.md") + let handWritten = + "# Project\n\nHand notes.\n\n\n# rules\n\nOriginal\n\n" + try fixture.write(handWritten, to: file) + #expect( + try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { + $0.kind == .foreignTarget && $0.path == file + }) + #expect(throws: InstructionError.unownedTargets(["AGENTS.md"])) { + try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + } + #expect(throws: InstructionError.unownedTargets(["AGENTS.md"])) { + try InstructionOperations.installResolvedReport(environment: fixture.environment) + } + #expect(try fixture.text() == handWritten) + _ = try InstructionOperations.updateInstalled( + environment: fixture.environment, apply: true, replace: true) + #expect(try fixture.text() == generated(["# rules\n\nOriginal"])) + } + + @Test func removeSelectsTheDeclaredReferenceBeforeASourceName() throws { + let fixture = try InstructionFixture() + try fixture.section("guide", heading: "# Shared Guide") + try fixture.commit() + try fixture.add(names: ["guide"]) + try fixture.own("guide", heading: "# Project Guide") + try fixture.addOwn(names: ["guide"]) + #expect( + try fixture.store().loadDeclaration().instructions?.sections == ["rules:guide", "guide"]) + try InstructionOperations.remove(names: ["guide"], environment: fixture.environment) + #expect(try fixture.store().loadDeclaration().instructions?.sections == ["rules:guide"]) + #expect(try fixture.text() == generated(["# Shared Guide\n\nOriginal"])) + } + + @Test func nestedTargetsStayInRealDirectoriesOfThisCheckout() throws { + let fixture = try InstructionFixture() + let sources = fixture.project.appendingPathComponent("Sources") + try FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: fixture.project.appendingPathComponent("Alias"), withDestinationURL: sources) + try fixture.own("alias", paths: ["Alias/**"]) + #expect(throws: CoreError.self) { try fixture.addOwn(names: ["alias"]) } + try fixture.write( + "gitdir: elsewhere\n", to: fixture.project.appendingPathComponent("vendor/lib/.git")) + try fixture.own("vendor", paths: ["vendor/lib/**"]) + #expect(throws: CoreError.self) { try fixture.addOwn(names: ["vendor"]) } + for path in ["Sources/AGENTS.md", "vendor/lib/AGENTS.md"] { + #expect( + !FileManager.default.fileExists(atPath: fixture.project.appendingPathComponent(path).path)) + } + } + + @Test func installRestoresTheLockedClaudeImport() throws { + let fixture = try InstructionFixture() + try fixture.section("rules") + try fixture.commit() + let directory = fixture.project.appendingPathComponent(".claude/CLAUDE.md") + try fixture.write("# Claude\n\nCustom.\n", to: directory) + try fixture.add() + #expect( + try fixture.store().loadResolved().instructions.targets[".claude/CLAUDE.md"]?.import + == "../AGENTS.md") + try FileManager.default.removeItem(at: directory) + let root = fixture.project.appendingPathComponent("CLAUDE.md") + try fixture.write("# Root\n", to: root) + _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) + #expect(try String(contentsOf: root, encoding: .utf8) == "# Root\n") + #expect(try String(contentsOf: directory, encoding: .utf8).contains("@../AGENTS.md")) + } + + @Test func unrelatedOwnFilesDoNotAffectLockedOrSelectedOnes() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.addOwn(names: ["guide"]) + try fixture.write( + "# Draft without front matter\n", + to: fixture.project.appendingPathComponent(".agent/instructions/draft.md")) + #expect(throws: Never.self) { + _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) + } + #expect(try !InstructionOperations.updateInstalled(environment: fixture.environment).hasChanges) + #expect(throws: InstructionError.self) { + try InstructionOperations.listOwn(environment: fixture.environment) + } + let mapping = InstructionOperations.export( + projectRoots: [fixture.project], environment: fixture.environment)[1] + #expect(mapping.unplaced.isEmpty) + #expect(mapping.targets.map { $0.sections.map(\.name) } == [["guide"]]) + } + + @Test func ownInstructionsContainerCannotBeASymbolicLink() throws { + let fixture = try InstructionFixture() + let units = fixture.project.appendingPathComponent("docs/units") + try fixture.write(unitText("guide"), to: units.appendingPathComponent("guide.md")) + try FileManager.default.createDirectory( + at: fixture.project.appendingPathComponent(".agent"), withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: fixture.project.appendingPathComponent(".agent/instructions"), withDestinationURL: units) + #expect(throws: CoreError.self) { + try InstructionOperations.listOwn(environment: fixture.environment) + } + #expect(throws: CoreError.self) { try fixture.addOwn(names: ["guide"]) } + } + + @Test func linksResolveSymbolicLinksBeforeParentSegmentsAndRejectRawHTML() throws { + let fixture = try InstructionFixture() + let outside = fixture.root.appendingPathComponent("outside/subdir") + try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink( + at: fixture.project.appendingPathComponent("link"), withDestinationURL: outside) + let readme = fixture.project.appendingPathComponent("README.md") + try fixture.write("Read me.\n", to: readme) + try fixture.own("parent", body: "[Read](link/../README.md)") + #expect(throws: InstructionError.self) { try fixture.addOwn(names: ["parent"]) } + try fixture.own("html", body: "Read") + #expect(throws: InstructionError.self) { try fixture.addOwn(names: ["html"]) } + try fixture.own("checks", body: "[Read](README.md)") + try fixture.addOwn(names: ["checks"]) + try FileManager.default.removeItem(at: readme) + #expect( + try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { + $0.kind == .invalidLink + }) + } + + @Test func doctorReportsChangedOwnFilesUsedOnlyByPrompts() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.write( + "{\"instructions\": {\"sections\": [], \"chatgpt\": {\"weekly\": {\"sections\": [\"guide\"]}}}}\n", + to: fixture.store().declarationURL) + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect( + try fixture.store().loadResolved().instructions.chatgpt["weekly"]?.sections.map(\.name) + == ["guide"]) + try fixture.own("guide", body: "Edited") + #expect( + try InstructionOperations.doctor(environment: fixture.environment).diagnostics.contains { + $0.kind == .ownChanged + }) + } + + @Test func doctorReportsClaudeFilesThatHideNestedTargets() throws { + let fixture = try InstructionFixture() + let sources = fixture.project.appendingPathComponent("Sources") + try FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true) + try fixture.own("swift", paths: ["Sources/**"]) + try fixture.addOwn(names: ["swift"]) + func forwarding() throws -> [URL?] { + try InstructionOperations.doctor(environment: fixture.environment).diagnostics + .filter { $0.kind == .claudeForwarding }.map(\.path) + } + #expect(try forwarding().isEmpty) + try fixture.write("# Root\n", to: fixture.project.appendingPathComponent("CLAUDE.md")) + #expect(try forwarding() == [sources.appendingPathComponent("AGENTS.md")]) + try fixture.write("# Sources\n", to: sources.appendingPathComponent("CLAUDE.md")) + #expect(try forwarding() == [sources.appendingPathComponent("CLAUDE.md")]) + try fixture.write("@AGENTS.md\n", to: sources.appendingPathComponent("CLAUDE.md")) + #expect(try forwarding().isEmpty) + } + + @Test func discoverySkipsGeneratedTargetNames() throws { + let fixture = try InstructionFixture() + try fixture.section("rules") + try fixture.write( + generated(["# Scoped\n\nFor instructions files."]), + to: fixture.repo.appendingPathComponent("instructions/AGENTS.md")) + try fixture.commit() + let units = try InstructionOperations.list( + source: SourceDeclaration(kind: .local, location: fixture.repo.path), + environment: fixture.environment) + #expect(units.map(\.record.name) == ["rules"]) + } + + @Test func exportPlacesUserSectionsWithoutTheirContent() throws { + let fixture = try InstructionFixture() + try fixture.section("rules") + try fixture.commit() + try fixture.add(scope: .user, agents: [.codex]) + try FileManager.default.removeItem(at: fixture.store(.user).cacheDirectory) + let user = InstructionOperations.export(projectRoots: [], environment: fixture.environment)[0] + #expect(user.unplaced.isEmpty) + #expect(user.targets.map { $0.sections.map(\.name) } == [["rules"]]) + } +} diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index de9338b..a4d54a7 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -45,6 +45,23 @@ struct TargetLifecycleTests { }) } + @Test func updatesKeepADeclarationWhoseContentIsUnchanged() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + let declaration = + "{\n \"instructions\": {\"agents\": [\"codex\"], \"sections\": [\"guide\"]}\n}\n" + let file = fixture.store().declarationURL + try fixture.write(declaration, to: file) + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try String(contentsOf: file, encoding: .utf8) == declaration) + #expect(try fixture.text() == generated(["# guide\n\nOriginal"])) + _ = try InstructionOperations.updateInstalled( + agents: [.codex, .geminiCLI], environment: fixture.environment, apply: true) + #expect( + try fixture.store().loadDeclaration().instructions?.agents == [.codex, .geminiCLI]) + #expect(try String(contentsOf: file, encoding: .utf8) != declaration) + } + @Test func pathsPlaceSectionsInNestedTargets() throws { let fixture = try InstructionFixture() try FileManager.default.createDirectory( From 66d75ffc409c4624f7e6adc31b763ffe8e369456 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:20:36 +0800 Subject: [PATCH 04/18] fix(instructions): keep selection, restore and watch to their inputs - Adding named own files reads only those files. - Install leaves a deleted locked Claude import file deleted. - Watch skips AGENTS.md and GEMINI.md in containers, as discovery does. - State which containers cannot hold targets, and keep a retired target that differs from its lock without writing over it. --- Documentation/Architecture/Instructions.md | 23 ++++++++++------- Documentation/Proposals/AgentInstructions.md | 4 ++- Sources/AgentsCore/WatchOperations.swift | 5 +++- .../InstructionModels.swift | 2 +- .../InstructionOperations.swift | 5 +++- .../InstructionTargets.swift | 13 +++++++--- .../OwnershipAndPlacementTests.swift | 25 ++++++++++++++++--- .../WatchSubscriptionTests.swift | 5 +++- 8 files changed, 60 insertions(+), 22 deletions(-) diff --git a/Documentation/Architecture/Instructions.md b/Documentation/Architecture/Instructions.md index 93a116f..202f106 100644 --- a/Documentation/Architecture/Instructions.md +++ b/Documentation/Architecture/Instructions.md @@ -29,20 +29,22 @@ and a pattern that starts with a wildcard yields the project root. Discovery reads `.md` files below `instructions/` and `.agents/instructions/` of the source's search `path`, recursively. A name is the container-relative path without `.md`; each segment uses lowercase letters, digits and hyphens. -`AGENTS.md` and `GEMINI.md` are target names, so discovery skips them; a -project can scope sections to its own container. A symbolic link at or below +`AGENTS.md` and `GEMINI.md` are target names, so discovery and watch skip them; +a file another scope generated in a container is never read as an instructions +file. A symbolic link at or below the search path, an invalid name and a name in both containers are errors. Instructions require Git sources. Local sources identify the repository root; use `path` to move its search root. Discovery reads committed trees even when the working tree is dirty. Each section and prompt section has its own -revision, path and original-byte hash. Source containers cannot hold targets. +revision, path and original-byte hash. A container of a local source declared +in the same scope cannot hold a target. A project's own files live in `.agent/instructions/` and are referenced by bare name; `alias:name` references a declared source. Own files are read from the working tree as it is. Their lock records have source `.`, the project-relative path and the hash, and no revision. Resolution and restore read only the named -file, `.agent/instructions/.md`, so other files in the container do not -affect them. Restoring a lock fails with `InstructionError.ownChanged` when an +file, `.agent/instructions/.md`, and so does adding named files, so other +files in the container affect only listing. Restoring a lock fails with `InstructionError.ownChanged` when an own file's hash changed; update reads the current file. `add(InstructionAddOptions, beforeApply:)` accepts a source alias or string, @@ -136,12 +138,14 @@ are not modified, and doctor reports one that hides a generated target. An `agents` argument sets the complete instruction recipient list. A name to remove that equals a declared reference, such as an own file's bare name or `alias:name`, selects that reference; another bare name must match exactly one -source reference. Removal also removes those sections from prompts. +source reference. Removal also removes those sections from prompts. Empty +prompts are removed. Other source declarations and skill records remain +available to their owners. + Export maps a user target to every locked section from the lock alone. A project section's placement needs its `paths`, read from the working tree or the cache without fetching; a section whose content is unavailable is listed as -unplaced. Empty prompts are removed. Other source -declarations and skill records remain available to their owners. +unplaced. Planning validates required content before applying. Reports include old and new section records, target before/after bytes and recipients, drift, foreign @@ -187,7 +191,8 @@ including in projects with no state directory. Install renders the locked sections into the locked targets and Claude import files, verifies every rendering against its locked hash before replacement, and -restores drifted files; it never recomputes forwarding or placement. Lost-lock update +restores drifted files; it never recomputes forwarding or placement, and a +locked Claude import file the owner deleted stays deleted. Lost-lock update reports the comparison; apply keeps identical files, replaces differing generated files, takes over others only with `replace`, and records targets as `created: false`. Without a lock entry a file is never deleted. diff --git a/Documentation/Proposals/AgentInstructions.md b/Documentation/Proposals/AgentInstructions.md index 2d67e00..1761129 100644 --- a/Documentation/Proposals/AgentInstructions.md +++ b/Documentation/Proposals/AgentInstructions.md @@ -136,7 +136,9 @@ paths: ["Sources/**/*.swift"] names a file, such as "run the checks in `CONTRIBUTING.md`", refers to the target's own files. -A source's instructions container is never itself a target location. +A container of a local source declared in the same scope is never a target +location. Discovery skips `AGENTS.md` and `GEMINI.md`, so a file another scope +generates in a container is never read as an instructions file. | Source kind | Pinned by | Notes | | --- | --- | --- | diff --git a/Sources/AgentsCore/WatchOperations.swift b/Sources/AgentsCore/WatchOperations.swift index d7221fe..100651c 100644 --- a/Sources/AgentsCore/WatchOperations.swift +++ b/Sources/AgentsCore/WatchOperations.swift @@ -349,7 +349,10 @@ public struct WatchOperations: Sendable { try collect(handle.child(file), prefix: prefix + file + "/") continue } - guard file.hasSuffix(".md") else { continue } + // Target names are never instructions files, as in discovery. + guard file.hasSuffix(".md"), !["AGENTS.md", "GEMINI.md"].contains(file) else { + continue + } let key = WatchItemKey(kind: .instructions, name: prefix + String(file.dropLast(3))) guard result[key] == nil else { throw CoreError.invalidSource("duplicate instructions name: \(key.name)") diff --git a/Sources/AgentsInstructions/InstructionModels.swift b/Sources/AgentsInstructions/InstructionModels.swift index 22fb9fb..7451983 100644 --- a/Sources/AgentsInstructions/InstructionModels.swift +++ b/Sources/AgentsInstructions/InstructionModels.swift @@ -80,7 +80,7 @@ public enum InstructionError: Error, Sendable, Equatable, CustomStringConvertibl case .invalidAssembly: return "The assembled Markdown does not have the expected structure." case .invalidLockedBlock: - return "The locked content does not match its recorded hash." + return "The lock's targets or recorded hashes do not match what its sections render." case .invalidLinks(let problems): return problems.map { "\($0.target): link '\($0.destination)' \($0.reason)" } .joined(separator: "\n") diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 292b866..493d824 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -35,7 +35,10 @@ public enum InstructionOperations { if options.source == InstructionSources.own { id = InstructionSources.own alias = nil - available = try sources.own() + // Named files are read alone, so an unfinished draft beside them does not stop the add. + available = + options.names.isEmpty || options.listOnly + ? try sources.own() : try options.names.map(sources.own(named:)) } else { let source: SourceDeclaration do { diff --git a/Sources/AgentsInstructions/InstructionTargets.swift b/Sources/AgentsInstructions/InstructionTargets.swift index 8a58bf1..12a5971 100644 --- a/Sources/AgentsInstructions/InstructionTargets.swift +++ b/Sources/AgentsInstructions/InstructionTargets.swift @@ -73,10 +73,15 @@ struct InstructionTargets { guard store.scope == .project, let path = ClaudeInstructionPath(rawValue: key), reference == String(path.importLine.dropFirst()) else { throw CoreError.invalidState("invalid Claude forwarding target") } - let edit = try Self.importBlock(in: before ?? Data(), at: path) - after = edit.bytes - targets[key]?.blockHash = edit.blockHash - targets[key]?.created = old?.created ?? (before == nil) + if restoring, before == nil { + // The owner deleted the Claude file; install does not recreate it. + after = nil + } else { + let edit = try Self.importBlock(in: before ?? Data(), at: path) + after = edit.bytes + targets[key]?.blockHash = edit.blockHash + targets[key]?.created = old?.created ?? (before == nil) + } } else if let text = rendered[key] { guard store.scope == .user || directoryExists(of: file) else { throw CoreError.notFound("the directory of instruction target \(key)") diff --git a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift index 55c6e54..f13f9f8 100644 --- a/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift +++ b/Tests/AgentsInstructionsTests/OwnershipAndPlacementTests.swift @@ -30,6 +30,19 @@ struct OwnershipAndPlacementTests { #expect(try fixture.text() == generated(["# rules\n\nOriginal"])) } + @Test func retiringATargetNeverWritesOverAFileThatDiffersFromItsLock() throws { + let fixture = try InstructionFixture() + try fixture.own("guide") + try fixture.addOwn(names: ["guide"]) + let handWritten = "# Project\n\nHand notes.\n" + try fixture.write(handWritten, to: fixture.project.appendingPathComponent("AGENTS.md")) + let report = try InstructionOperations.remove( + names: ["guide"], environment: fixture.environment) + #expect(report.targets.first?.changed == false) + #expect(try fixture.text() == handWritten) + #expect(try fixture.store().loadResolved().instructions.targets.isEmpty) + } + @Test func removeSelectsTheDeclaredReferenceBeforeASourceName() throws { let fixture = try InstructionFixture() try fixture.section("guide", heading: "# Shared Guide") @@ -62,7 +75,7 @@ struct OwnershipAndPlacementTests { } } - @Test func installRestoresTheLockedClaudeImport() throws { + @Test func installKeepsTheLockedClaudeImportWithoutRecomputingIt() throws { let fixture = try InstructionFixture() try fixture.section("rules") try fixture.commit() @@ -75,9 +88,10 @@ struct OwnershipAndPlacementTests { try FileManager.default.removeItem(at: directory) let root = fixture.project.appendingPathComponent("CLAUDE.md") try fixture.write("# Root\n", to: root) - _ = try InstructionOperations.installResolvedReport(environment: fixture.environment) + let report = try InstructionOperations.installResolvedReport(environment: fixture.environment) + #expect(report.targets.first { $0.target == ".claude/CLAUDE.md" }?.drift == .missing) #expect(try String(contentsOf: root, encoding: .utf8) == "# Root\n") - #expect(try String(contentsOf: directory, encoding: .utf8).contains("@../AGENTS.md")) + #expect(!FileManager.default.fileExists(atPath: directory.path)) } @Test func unrelatedOwnFilesDoNotAffectLockedOrSelectedOnes() throws { @@ -94,10 +108,13 @@ struct OwnershipAndPlacementTests { #expect(throws: InstructionError.self) { try InstructionOperations.listOwn(environment: fixture.environment) } + try fixture.own("second") + try fixture.addOwn(names: ["second"]) + #expect(throws: InstructionError.self) { try fixture.addOwn(names: []) } let mapping = InstructionOperations.export( projectRoots: [fixture.project], environment: fixture.environment)[1] #expect(mapping.unplaced.isEmpty) - #expect(mapping.targets.map { $0.sections.map(\.name) } == [["guide"]]) + #expect(mapping.targets.map { $0.sections.map(\.name) } == [["guide", "second"]]) } @Test func ownInstructionsContainerCannotBeASymbolicLink() throws { diff --git a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift index 5d080ee..de156ee 100644 --- a/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift +++ b/Tests/AgentsSkillsTests/WatchSubscriptionTests.swift @@ -148,15 +148,18 @@ struct WatchSubscriptionTests { #expect(Set(status.changes.map(\.name)) == ["inside", "rule"]) } - @Test func namesNestedInstructionsByTheirContainerPath() throws { + @Test func namesNestedInstructionsByTheirContainerPathAndSkipsTargets() throws { let fixture = try SkillFixture() try write(fixture.repo.appendingPathComponent("instructions/epd/review.md"), "old") try write(fixture.repo.appendingPathComponent("instructions/notes.txt"), "ignored") + try write(fixture.repo.appendingPathComponent("instructions/AGENTS.md"), "generated") + try write(fixture.repo.appendingPathComponent(".agents/instructions/AGENTS.md"), "generated") try fixture.commit() let watch = SkillOperations.watchOperations() try watch.add(fixture.repo.path, alias: "source", environment: fixture.environment) try write(fixture.repo.appendingPathComponent("instructions/epd/review.md"), "new") try write(fixture.repo.appendingPathComponent("instructions/notes.txt"), "still ignored") + try write(fixture.repo.appendingPathComponent("instructions/AGENTS.md"), "regenerated") try fixture.commit() let status = try #require(watch.status(environment: fixture.environment).first) #expect(status.changes.map(\.name) == ["epd/review"]) From 50d44bab4f9069194c95b2a2b8f8805baf6cf186 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 18:52:44 +0800 Subject: [PATCH 05/18] docs: generate AGENTS.md from instruction units Declare this repository's guide with the agents-tools shared package route and test isolation units, and track the declaration and lock. --- .agent/agents.json | 20 +++++++ .agent/agents.resolved | 54 ++++++++++++++++++ .agent/instructions/guide.md | 25 ++++++++ .gitignore | 5 +- AGENTS.md | 108 ++++++++++++----------------------- 5 files changed, 140 insertions(+), 72 deletions(-) create mode 100644 .agent/agents.json create mode 100644 .agent/agents.resolved create mode 100644 .agent/instructions/guide.md diff --git a/.agent/agents.json b/.agent/agents.json new file mode 100644 index 0000000..b01d82e --- /dev/null +++ b/.agent/agents.json @@ -0,0 +1,20 @@ +{ + "sources": { + "agents-tools": { + "git": "github.com/agents-tools/.github", + "path": ".agent", + "revision": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6" + } + }, + "instructions": { + "agents": [ + "claude-code", + "codex" + ], + "sections": [ + "guide", + "agents-tools:shared/swift-package-route", + "agents-tools:shared/swift-package-tests" + ] + } +} diff --git a/.agent/agents.resolved b/.agent/agents.resolved new file mode 100644 index 0000000..fc510d6 --- /dev/null +++ b/.agent/agents.resolved @@ -0,0 +1,54 @@ +{ + "instructions" : { + "chatgpt" : { + + }, + "sections" : [ + { + "hash" : "sha256:f173982b030ad0468dbc05b28d223443e21fdcd048b3b663d0ab8098122a776d", + "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" : "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6", + "source" : "github.com/agents-tools/.github" + }, + { + "hash" : "sha256:5d9f40d101938d2805482b9a147397bc07e9c3c9223cfe040f0905cb6c746825", + "name" : "shared/swift-package-tests", + "path" : ".agent/instructions/shared/swift-package-tests.md", + "revision" : "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6", + "source" : "github.com/agents-tools/.github" + } + ], + "targets" : { + "AGENTS.md" : { + "agents" : [ + "claude-code", + "codex" + ], + "blockHash" : "sha256:92e390f948a5dbbd9bade19698b6ad22c07f08dd993512005bd7f28a74a672d5", + "created" : false, + "headingOffset" : 0 + } + } + }, + "skills" : { + + }, + "sources" : { + "github.com/agents-tools/.github" : { + "kind" : "git", + "path" : ".agent", + "requirement" : { + "revision" : "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6" + }, + "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..a171c74 --- /dev/null +++ b/.agent/instructions/guide.md @@ -0,0 +1,25 @@ +--- +description: Keep agents-tools/core's modules, dependency direction and public surface within their boundaries. +--- +# core Agent Guide + +## Task Route + +- Run the build, test and strict formatting checks in `README.md#development` + before handoff. +- Community files and templates are organization defaults in + `agents-tools/.github`; this repository keeps `CODEOWNERS`, the Dependabot + configuration and workflow callers under `.github/`. + +## Module Boundaries + +- Keep shared primitives, source resolution, registry, lock and watch behavior + in `Sources/AgentsCore`, and skill discovery, installation and lifecycle in + `Sources/AgentsSkills`. `AgentsCore` must not depend on `AgentsSkills`; Yams + belongs to `AgentsSkills`. +- Keep command parsing and terminal behavior in the consuming repositories. +- Expose consumer operations and their models publicly; keep implementation + details internal, or package-visible when shared between targets. +- Keep package-domain prefixes out of internal target names unless the package + boundary stops making that context clear. +- Disable automatic maintenance and gc in fixture Git repositories. diff --git a/.gitignore b/.gitignore index d29780b..f27a062 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,4 @@ .DS_Store -.agent/ .vscode/ /.build /Packages @@ -9,3 +8,7 @@ DerivedData/ .swiftpm/configuration/registries.json .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata .netrc +/.agent/* +!/.agent/instructions/ +!/.agent/agents.json +!/.agent/agents.resolved diff --git a/AGENTS.md b/AGENTS.md index dd22325..700df70 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,81 +1,47 @@ -# core Agent Guide - -Read `README.md` first for repository purpose, library API, and development -entry points. + -## First-Principles Work - -- Name the behavior, root cause, invariant, owner, data flow, and validation - before changing reusable files. -- Change the owning layer, not the nearest convenient file. -- Keep changes traceable to the request, source evidence, or owning invariant. -- Validate with package-local checks when behavior changes. +# core Agent Guide ## Task Route -- For documentation placement, read `Documentation/README.md` before editing. -- For current package structure, read `Documentation/Architecture/README.md` - and the relevant architecture files. -- For unresolved design work, use `Documentation/Proposals/*`. -- For durable rationale, use `Documentation/Decisions/*`. -- For migration notes, use `Documentation/Migrations/*`. -- For retired material, use `Documentation/Archive/*`. -- For supporting details and examples, use `Documentation/Reference/*`. +- Run the build, test and strict formatting checks in `README.md#development` + before handoff. - Community files and templates are organization defaults in - `agents-tools/.github`; this repository keeps `CODEOWNERS`, Dependabot + `agents-tools/.github`; this repository keeps `CODEOWNERS`, the Dependabot configuration and workflow callers under `.github/`. -- Follow the organization [maintenance change flow](https://github.com/agents-tools/.github/blob/master/MAINTENANCE.md#change-flow). - -## Authority - -- `AGENTS.md` is the agent guide for repository work. -- `README` files index scope and placement. -- `Documentation/Architecture/*` states current truth. -- `Documentation/Proposals/*` is design-in-progress. -- `Documentation/Decisions/*`, `Documentation/Migrations/*`, and - `Documentation/Archive/*` are history. -- `.github/*` is GitHub-facing workflow metadata. - -## Boundary Guardrails - -- Do not promote machine-local paths, one-run state, fixture-only values, or - temporary execution state into reusable docs, scripts, templates, or - automation. -- If a value changes by input or environment, pass it in, configure it, derive - it, or link to the owning artifact. -- Keep command parsing and terminal behavior in consuming repositories. -- Keep shared source, registry, lock, and watch behavior in `AgentsCore`; skill - discovery and lifecycle behavior belongs in `AgentsSkills`. -- `AgentsCore` must not depend on `AgentsSkills`. Yams belongs to `AgentsSkills`. -## Tests - -- Run the build, test and strict formatting checks in - [README.md](README.md#development) before handoff. The required CI contexts - are `policy / policy` and `validate / result`; keep their caller job - IDs and shared workflow pins consistent with the - [shared workflow reference](https://github.com/agents-tools/github-workflows#configuration). - Shared CI compiles and tests only with the latest stable Xcode selected in - `.github/swift-package.json`. - Render and check the social preview locally with the github-readme-design - toolchain against `agents-tools/.github`'s DESIGN, fonts and catalog; see - `Documentation/Reference/Presentation.md`. Commit the resulting assets. - For workflow edits, also run `actionlint` on every workflow. -- Pass an explicit initial branch when creating Git fixtures. -- Disable automatic maintenance and gc in fixture Git repositories. -- Each test that creates a temporary directory removes it. -- Run tests with agent configuration variables unset: - - ```bash - env -u CODEX_HOME -u CLAUDE_CONFIG_DIR -u XDG_CONFIG_HOME -u XDG_STATE_HOME -u XDG_CACHE_HOME swift test - ``` - -## Operating Notes +## Module Boundaries +- Keep shared primitives, source resolution, registry, lock and watch behavior + in `Sources/AgentsCore`, and skill discovery, installation and lifecycle in + `Sources/AgentsSkills`. `AgentsCore` must not depend on `AgentsSkills`; Yams + belongs to `AgentsSkills`. +- Keep command parsing and terminal behavior in the consuming repositories. +- Expose consumer operations and their models publicly; keep implementation + details internal, or package-visible when shared between targets. - Keep package-domain prefixes out of internal target names unless the package boundary stops making that context clear. -- Keep shared primitives and source resolution in `Sources/AgentsCore`. -- Keep skill discovery, installation, and orchestration in `Sources/AgentsSkills`. -- Expose consumer operations and their models publicly; keep implementation - details internal or package-visible when shared between the two targets. -- Run `swift test` before handing off behavior changes. +- Disable automatic maintenance and gc in fixture Git repositories. + +## 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. From 28abb80b396d7da963107e03e0583259f6bf9731 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:03:04 +0800 Subject: [PATCH 06/18] ci: pin shared workflows to the policy that accepts instruction files --- .github/workflows/ci.yml | 2 +- .github/workflows/source-policy.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0d9d6c8..fa6769d 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@ebd6af9164232217e2e243da0d9735544ae3a8f9 diff --git a/.github/workflows/source-policy.yml b/.github/workflows/source-policy.yml index 89a471f..aa9c969 100644 --- a/.github/workflows/source-policy.yml +++ b/.github/workflows/source-policy.yml @@ -17,7 +17,7 @@ concurrency: jobs: policy: if: github.event_name != 'push' || !github.event.deleted - uses: agents-tools/github-workflows/.github/workflows/policy.yml@3fb2887e2831d9d5a287af73819e2ba3a39d0045 + uses: agents-tools/github-workflows/.github/workflows/policy.yml@ebd6af9164232217e2e243da0d9735544ae3a8f9 with: allow-terms: | ChatGPT From 0a4c5608ac731489dfc0b8ad31d95f6da56daa73 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 19:23:39 +0800 Subject: [PATCH 07/18] docs(instructions): drop the vendor link from the design references --- Documentation/Proposals/AgentInstructions.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Documentation/Proposals/AgentInstructions.md b/Documentation/Proposals/AgentInstructions.md index 1761129..47351ee 100644 --- a/Documentation/Proposals/AgentInstructions.md +++ b/Documentation/Proposals/AgentInstructions.md @@ -618,7 +618,7 @@ working tree that another operation depends on. - Agents keep persistent instructions as one Markdown file per rule in a conventional directory: GitHub Copilot's [`.github/instructions/`](https://docs.github.com/en/copilot/concepts/prompting-and-context/custom-instructions), - Cursor's [`.cursor/rules/`](https://cursor.com/docs/context/rules) and + Cursor's `.cursor/rules/` and Claude Code's [`.claude/rules/`](https://code.claude.com/docs/en/memory). Instructions containers follow the same layout, with front matter as in Cursor's `.mdc` rules and `paths` as in Claude Code's path-scoped rules. From 063fecb6a70d0c3f5f9ccf2093bfc1dfd53cd5ed Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:09:19 +0800 Subject: [PATCH 08/18] fix(cache): keep dangling symbolic links that stay inside the tree A committed link to an uncommitted file made materialization reject the whole source, because Foundation resolves dangling links inconsistently. Links are now checked with the kernel's resolution and lexical targets: one that leaves the tree or resolves outside it is rejected, a dangling one inside is kept. Copied subtrees use the same rule. --- CHANGELOG.md | 3 ++ Sources/AgentsCore/FileTransaction.swift | 9 +++-- Sources/AgentsCore/PathSafety.swift | 32 +++++++++++++++++ Sources/AgentsCore/SourceCache.swift | 15 ++++---- Tests/AgentsCoreTests/SourceCacheTests.swift | 38 ++++++++++++++++++++ 5 files changed, 84 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97fb8e6..3569f95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,9 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ### Fixed +- Materializing a source and copying a subtree keep a dangling symbolic link + that stays inside, such as one to an uncommitted file, instead of rejecting + the whole source; a link that leaves the tree is still rejected. - Doctor's Codex size check counts only the project chain, as Codex does: the user file is loaded separately without a limit, separators are not counted, whitespace-only files add nothing, fallback names apply in every directory, diff --git a/Sources/AgentsCore/FileTransaction.swift b/Sources/AgentsCore/FileTransaction.swift index 2188e89..57c063b 100644 --- a/Sources/AgentsCore/FileTransaction.swift +++ b/Sources/AgentsCore/FileTransaction.swift @@ -335,18 +335,17 @@ package final class FileTransaction { return source.path } + /// A copied subtree keeps relative links that stay inside it, dangling ones included. private static func validateCopy(_ source: URL) throws { - let root = source.resolvingSymlinksInPath() - guard + guard let root = PathSafety.realPath(source.path), let entries = FileManager.default.enumerator( - at: root, includingPropertiesForKeys: [.isSymbolicLinkKey]) + at: URL(fileURLWithPath: root), includingPropertiesForKeys: [.isSymbolicLinkKey]) else { return } for case let entry as URL in entries { if try entry.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { entries.skipDescendants() let destination = try FileManager.default.destinationOfSymbolicLink(atPath: entry.path) - guard !destination.hasPrefix("/"), - PathSafety.isContained(entry.resolvingSymlinksInPath(), in: root) + guard !destination.hasPrefix("/"), try PathSafety.linkStaysInside(entry, root: root) else { throw CoreError.unsafePath("copy symlink escapes installed subtree: \(entry.path)") } diff --git a/Sources/AgentsCore/PathSafety.swift b/Sources/AgentsCore/PathSafety.swift index 4539448..8eed439 100644 --- a/Sources/AgentsCore/PathSafety.swift +++ b/Sources/AgentsCore/PathSafety.swift @@ -38,6 +38,38 @@ public enum PathSafety { return target } + /// Whether the symbolic link at `link` stays within the real directory `root`: its target, + /// applied to the link's real directory, does not leave `root`, and it does not resolve to an + /// existing path outside `root`. A dangling link inside `root` cannot be followed. + package static func linkStaysInside(_ link: URL, root: String) throws -> Bool { + let destination = try FileManager.default.destinationOfSymbolicLink(atPath: link.path) + guard let directory = realPath(link.deletingLastPathComponent().path) else { return false } + func inside(_ path: String) -> Bool { path == root || path.hasPrefix(root + "/") } + let lexical = lexicallyNormalized( + destination.hasPrefix("/") ? destination : directory + "/" + destination) + return inside(lexical) && (realPath(link.path).map(inside) ?? true) + } + + /// The path as the kernel resolves it for a reader, or nil when it does not exist. + package static func realPath(_ path: String) -> String? { + guard let real = realpath(path, nil) else { return nil } + defer { free(real) } + return String(cString: real) + } + + /// An absolute path with `.` and `..` segments applied without consulting the filesystem. + private static func lexicallyNormalized(_ path: String) -> String { + var parts: [Substring] = [] + for part in path.split(separator: "/") where part != "." { + if part == ".." { + _ = parts.popLast() + } else { + parts.append(part) + } + } + return "/" + parts.joined(separator: "/") + } + package static func isContained(_ target: URL, in base: URL) -> Bool { let basePath = base.standardizedFileURL.path let targetPath = target.standardizedFileURL.path diff --git a/Sources/AgentsCore/SourceCache.swift b/Sources/AgentsCore/SourceCache.swift index 1cb9844..2d28e27 100644 --- a/Sources/AgentsCore/SourceCache.swift +++ b/Sources/AgentsCore/SourceCache.swift @@ -707,18 +707,17 @@ package struct SourceCache { + FileHash.sha256Hex(data: Data(sourceID.utf8)) } + /// Rejects a symbolic link that can lead outside the extracted tree. A dangling link that stays + /// inside, such as one to an uncommitted file, cannot be followed and is kept. private func validateTree(_ tree: URL) throws { - guard + guard let root = PathSafety.realPath(tree.path), let enumerator = FileManager.default.enumerator( at: tree, includingPropertiesForKeys: [.isSymbolicLinkKey]) else { return } - for case let url as URL in enumerator { - if try url.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { - guard - PathSafety.isContained(url.resolvingSymlinksInPath(), in: tree.resolvingSymlinksInPath()) - else { - throw CoreError.unsafePath("source symlink escapes committed tree") - } + for case let url as URL in enumerator + where try url.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink == true { + guard try PathSafety.linkStaysInside(url, root: root) else { + throw CoreError.unsafePath("source symlink escapes committed tree") } } } diff --git a/Tests/AgentsCoreTests/SourceCacheTests.swift b/Tests/AgentsCoreTests/SourceCacheTests.swift index 099af10..f0122e9 100644 --- a/Tests/AgentsCoreTests/SourceCacheTests.swift +++ b/Tests/AgentsCoreTests/SourceCacheTests.swift @@ -49,6 +49,44 @@ struct SourceCacheTests { #expect(!FileManager.default.fileExists(atPath: tree.path)) } + @Test(arguments: [ + ("../missing/file.pdf", true), ("missing", true), ("../sub/file", true), ("../sub", true), + ("../../outside", false), ("/etc/hosts", false), ("/nonexistent/file", false), + ]) + func materializationKeepsInTreeLinksAndRejectsEscapes(_ destination: String, _ kept: Bool) + throws + { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let repo = root.appendingPathComponent("repo") + try FileManager.default.createDirectory( + at: repo.appendingPathComponent("sub"), withIntermediateDirectories: true) + try FileManager.default.createDirectory( + at: repo.appendingPathComponent("docs"), withIntermediateDirectories: true) + try Data("file".utf8).write(to: repo.appendingPathComponent("sub/file")) + try FileManager.default.createSymbolicLink( + atPath: repo.appendingPathComponent("docs/link").path, withDestinationPath: destination) + try initGitRepo(repo) + let environment = RuntimeEnvironment( + projectDirectory: root, homeDirectory: root.appendingPathComponent("home"), environment: [:]) + let cache = SourceCache(store: StateStore(scope: .project, environment: environment)) + let source = SourceDeclaration(kind: .local, location: repo.path) + let pin = try cache.resolve(source) + let materialize = { + try cache.materialize( + sourceID: source.identity(environment: environment), source: LockedSource(kind: .local), + revision: pin.revision) + } + if kept { + let tree = try materialize() + #expect( + try FileManager.default.destinationOfSymbolicLink( + atPath: tree.appendingPathComponent("docs/link").path) == destination) + } else { + #expect(throws: CoreError.self) { try materialize() } + } + } + @Test func resolvesBoundsAndIgnoresWorkingTreeChanges() throws { let root = try temporaryDirectory() defer { removeTemporaryDirectory(root) } From 38d667db287608c265d3bdf8cc727910b8ea1e9c Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:19:27 +0800 Subject: [PATCH 09/18] ci: pin shared workflows to the policy that keeps nested private state private --- .github/workflows/ci.yml | 2 +- .github/workflows/source-policy.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fa6769d..c3d22cc 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@ebd6af9164232217e2e243da0d9735544ae3a8f9 + uses: agents-tools/github-workflows/.github/workflows/swift-package.yml@d0d1fd91e655e6d230cf3d5085c1eb6f5f26d358 diff --git a/.github/workflows/source-policy.yml b/.github/workflows/source-policy.yml index aa9c969..b907378 100644 --- a/.github/workflows/source-policy.yml +++ b/.github/workflows/source-policy.yml @@ -17,7 +17,7 @@ concurrency: jobs: policy: if: github.event_name != 'push' || !github.event.deleted - uses: agents-tools/github-workflows/.github/workflows/policy.yml@ebd6af9164232217e2e243da0d9735544ae3a8f9 + uses: agents-tools/github-workflows/.github/workflows/policy.yml@d0d1fd91e655e6d230cf3d5085c1eb6f5f26d358 with: allow-terms: | ChatGPT From c62338c76461957f47a617b0e240414344dbff1c Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:19:27 +0800 Subject: [PATCH 10/18] docs: commit the project declaration and lock --- README.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 689ec6a..d680f05 100644 --- a/README.md +++ b/README.md @@ -117,8 +117,10 @@ requirement. Pin a reviewed revision when reproducibility is required. Use Project state lives in `.agent/agents.json`, `.agent/agents.resolved` and `.agent/agents.watch`. User state uses the same filenames under `~/.agents/`. -The respective `cache/` directory holds source mirrors and exact content. State -is local to its scope and should be ignored by version control. +The respective `cache/` directory holds source mirrors and exact content. A +project commits its `agents.json` declaration and `agents.resolved` lock; keep +`agents.watch`, `cache/`, `.agents.lock` and `transaction.json` out of version +control. The declaration records source aliases, requirements, skill selections and recipients. The version 1 lock records each skill's independent revision or From 7d57573f9ba7efe4f367d3474d462ebb53e327df Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:19:27 +0800 Subject: [PATCH 11/18] docs: ask for actionlint on workflow changes --- .agent/agents.resolved | 4 ++-- .agent/instructions/guide.md | 1 + AGENTS.md | 1 + 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.agent/agents.resolved b/.agent/agents.resolved index fc510d6..ac85af3 100644 --- a/.agent/agents.resolved +++ b/.agent/agents.resolved @@ -5,7 +5,7 @@ }, "sections" : [ { - "hash" : "sha256:f173982b030ad0468dbc05b28d223443e21fdcd048b3b663d0ab8098122a776d", + "hash" : "sha256:649e05046822eb7cc03e9f0008bb0924134598d163a80224496902208f2c7492", "name" : "guide", "path" : ".agent/instructions/guide.md", "source" : "." @@ -31,7 +31,7 @@ "claude-code", "codex" ], - "blockHash" : "sha256:92e390f948a5dbbd9bade19698b6ad22c07f08dd993512005bd7f28a74a672d5", + "blockHash" : "sha256:f680afe6322f036457d6f5296738912a482f48319ee11ba47932a9813b870add", "created" : false, "headingOffset" : 0 } diff --git a/.agent/instructions/guide.md b/.agent/instructions/guide.md index a171c74..f9daefc 100644 --- a/.agent/instructions/guide.md +++ b/.agent/instructions/guide.md @@ -7,6 +7,7 @@ description: Keep agents-tools/core's modules, dependency direction and public s - Run the build, test and strict formatting checks in `README.md#development` before handoff. +- For workflow changes, run `actionlint` on every workflow. - Community files and templates are organization defaults in `agents-tools/.github`; this repository keeps `CODEOWNERS`, the Dependabot configuration and workflow callers under `.github/`. diff --git a/AGENTS.md b/AGENTS.md index 700df70..fcdb664 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,6 +6,7 @@ - Run the build, test and strict formatting checks in `README.md#development` before handoff. +- For workflow changes, run `actionlint` on every workflow. - Community files and templates are organization defaults in `agents-tools/.github`; this repository keeps `CODEOWNERS`, the Dependabot configuration and workflow callers under `.github/`. From f81c9feb3e661da347c10a5915ee7b4dce706283 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 20:23:39 +0800 Subject: [PATCH 12/18] docs: route module boundaries to the package architecture --- .agent/agents.resolved | 4 ++-- .agent/instructions/guide.md | 10 +++------- AGENTS.md | 10 +++------- 3 files changed, 8 insertions(+), 16 deletions(-) diff --git a/.agent/agents.resolved b/.agent/agents.resolved index ac85af3..3223faa 100644 --- a/.agent/agents.resolved +++ b/.agent/agents.resolved @@ -5,7 +5,7 @@ }, "sections" : [ { - "hash" : "sha256:649e05046822eb7cc03e9f0008bb0924134598d163a80224496902208f2c7492", + "hash" : "sha256:b954b104c6cf0639214a105a846d4fc8e73fd55f14eb695f407f942b905bf22e", "name" : "guide", "path" : ".agent/instructions/guide.md", "source" : "." @@ -31,7 +31,7 @@ "claude-code", "codex" ], - "blockHash" : "sha256:f680afe6322f036457d6f5296738912a482f48319ee11ba47932a9813b870add", + "blockHash" : "sha256:a025a4ce7d403ace72e30ffe5b2922f571c44f0f6ea52998f5a1bfe6a7ee3fd6", "created" : false, "headingOffset" : 0 } diff --git a/.agent/instructions/guide.md b/.agent/instructions/guide.md index f9daefc..a258b2f 100644 --- a/.agent/instructions/guide.md +++ b/.agent/instructions/guide.md @@ -14,13 +14,9 @@ description: Keep agents-tools/core's modules, dependency direction and public s ## Module Boundaries -- Keep shared primitives, source resolution, registry, lock and watch behavior - in `Sources/AgentsCore`, and skill discovery, installation and lifecycle in - `Sources/AgentsSkills`. `AgentsCore` must not depend on `AgentsSkills`; Yams - belongs to `AgentsSkills`. -- Keep command parsing and terminal behavior in the consuming repositories. -- Expose consumer operations and their models publicly; keep implementation - details internal, or package-visible when shared between targets. +- Keep each target's responsibilities, dependencies and access levels as + `Documentation/Architecture/Package.md` states, and update it with the + dependency graph in `Package.swift`. - Keep package-domain prefixes out of internal target names unless the package boundary stops making that context clear. - Disable automatic maintenance and gc in fixture Git repositories. diff --git a/AGENTS.md b/AGENTS.md index fcdb664..f31760a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,13 +13,9 @@ ## Module Boundaries -- Keep shared primitives, source resolution, registry, lock and watch behavior - in `Sources/AgentsCore`, and skill discovery, installation and lifecycle in - `Sources/AgentsSkills`. `AgentsCore` must not depend on `AgentsSkills`; Yams - belongs to `AgentsSkills`. -- Keep command parsing and terminal behavior in the consuming repositories. -- Expose consumer operations and their models publicly; keep implementation - details internal, or package-visible when shared between targets. +- Keep each target's responsibilities, dependencies and access levels as + `Documentation/Architecture/Package.md` states, and update it with the + dependency graph in `Package.swift`. - Keep package-domain prefixes out of internal target names unless the package boundary stops making that context clear. - Disable automatic maintenance and gc in fixture Git repositories. From 318acf9da45010c1c1497943e8b0075019a4d16c Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:34:03 +0800 Subject: [PATCH 13/18] fix(cache): resolve links inside the root as the kernel does Lexical normalization treated 'here/..' as a no-op even when 'here' is a link, so a dangling link such as 'here/here/../../settings.json' in a skill passed validation and, once copied, read a file above the installed skill. Links are now resolved component by component from their directory, following links inside the root: a step above the root, an absolute destination or a loop is rejected, and reaching a missing entry, which the tree lacks wherever it is placed, is safe. --- Sources/AgentsCore/PathSafety.swift | 57 ++++++++++++------- Tests/AgentsCoreTests/PathSafetyTests.swift | 28 +++++++++ .../RetainedLifecycleTests.swift | 18 ++++++ 3 files changed, 81 insertions(+), 22 deletions(-) diff --git a/Sources/AgentsCore/PathSafety.swift b/Sources/AgentsCore/PathSafety.swift index 8eed439..6a75196 100644 --- a/Sources/AgentsCore/PathSafety.swift +++ b/Sources/AgentsCore/PathSafety.swift @@ -38,16 +38,42 @@ public enum PathSafety { return target } - /// Whether the symbolic link at `link` stays within the real directory `root`: its target, - /// applied to the link's real directory, does not leave `root`, and it does not resolve to an - /// existing path outside `root`. A dangling link inside `root` cannot be followed. + /// Whether the symbolic link at `link` stays inside the real directory `root` wherever that + /// tree is placed. Its destination is resolved from the link's directory as the kernel does, + /// following links inside `root`; the link stays inside when resolution reaches a missing entry, + /// which the tree lacks in any placement, or ends without leaving `root`. An absolute + /// destination, a step above `root` and a link loop leave it. package static func linkStaysInside(_ link: URL, root: String) throws -> Bool { - let destination = try FileManager.default.destinationOfSymbolicLink(atPath: link.path) - guard let directory = realPath(link.deletingLastPathComponent().path) else { return false } - func inside(_ path: String) -> Bool { path == root || path.hasPrefix(root + "/") } - let lexical = lexicallyNormalized( - destination.hasPrefix("/") ? destination : directory + "/" + destination) - return inside(lexical) && (realPath(link.path).map(inside) ?? true) + guard let directory = realPath(link.deletingLastPathComponent().path), + directory == root || directory.hasPrefix(root + "/") + else { return false } + var current = directory.dropFirst(root.count).split(separator: "/").map(String.init) + var pending = try components(FileManager.default.destinationOfSymbolicLink(atPath: link.path)) + var expansions = 0 + while !pending.isEmpty { + guard let next = pending.removeFirst() else { return false } + if next == "." { continue } + if next == ".." { + guard current.popLast() != nil else { return false } + continue + } + let path = ([root] + current + [next]).joined(separator: "/") + if let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: path) { + expansions += 1 + guard expansions <= 32 else { return false } + pending = components(destination) + pending + continue + } + guard FileManager.default.fileExists(atPath: path) else { return true } + current.append(next) + } + return true + } + + /// A relative destination's components; nil marks an absolute destination. + private static func components(_ destination: String) -> [String?] { + guard !destination.hasPrefix("/") else { return [nil] } + return destination.split(separator: "/").map(String.init) } /// The path as the kernel resolves it for a reader, or nil when it does not exist. @@ -57,19 +83,6 @@ public enum PathSafety { return String(cString: real) } - /// An absolute path with `.` and `..` segments applied without consulting the filesystem. - private static func lexicallyNormalized(_ path: String) -> String { - var parts: [Substring] = [] - for part in path.split(separator: "/") where part != "." { - if part == ".." { - _ = parts.popLast() - } else { - parts.append(part) - } - } - return "/" + parts.joined(separator: "/") - } - package static func isContained(_ target: URL, in base: URL) -> Bool { let basePath = base.standardizedFileURL.path let targetPath = target.standardizedFileURL.path diff --git a/Tests/AgentsCoreTests/PathSafetyTests.swift b/Tests/AgentsCoreTests/PathSafetyTests.swift index cd0e0aa..e80f16d 100644 --- a/Tests/AgentsCoreTests/PathSafetyTests.swift +++ b/Tests/AgentsCoreTests/PathSafetyTests.swift @@ -5,6 +5,34 @@ import Testing @Suite("Path Safety And Sanitization") struct PathSafetyAndSanitizationTests { + @Test func linksStayInsideOnlyWhenResolutionWithinTheRootCannotLeaveIt() throws { + let root = try temporaryDirectory() + defer { removeTemporaryDirectory(root) } + let repo = root.appendingPathComponent("repo") + let skill = repo.appendingPathComponent("skills/demo") + try FileManager.default.createDirectory( + at: skill.appendingPathComponent("docs"), withIntermediateDirectories: true) + try Data("guide".utf8).write(to: skill.appendingPathComponent("docs/guide.md")) + let links = [ + "here": ".", "leak": "here/here/../../settings.json", "guide": "here/docs/guide.md", + "pdf": "../../library/missing.pdf", "up": "../../../outside", "absolute": "/etc/hosts", + "loop": "loop-back", "loop-back": "loop", + ] + for (name, destination) in links { + try FileManager.default.createSymbolicLink( + atPath: skill.appendingPathComponent(name).path, withDestinationPath: destination) + } + func stays(_ name: String, in base: URL) throws -> Bool { + try PathSafety.linkStaysInside( + skill.appendingPathComponent(name), root: try #require(PathSafety.realPath(base.path))) + } + for name in ["here", "guide"] { #expect(try stays(name, in: skill)) } + for name in ["leak", "pdf", "up", "absolute", "loop"] { #expect(try !stays(name, in: skill)) } + // In the whole repository, the same dangling links stay inside and cannot be followed out. + for name in ["leak", "pdf"] { #expect(try stays(name, in: repo)) } + #expect(try !stays("up", in: repo)) + } + @Test func sanitizesSkillNamesForFilesystemPaths() { let cases: [(String, String)] = [ ("MySkill", "myskill"), diff --git a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift index 9a1e046..3da70f2 100644 --- a/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift +++ b/Tests/AgentsSkillsTests/RetainedLifecycleTests.swift @@ -33,6 +33,24 @@ struct RetainedLifecycleTests { #expect(try fixture.store().loadDeclaration().sources.values.first?.path == "skills/demo") } + @Test func copyInstallRejectsADanglingLinkThatResolvesAboveTheSkill() throws { + let fixture = try SkillFixture() + try fixture.skill("demo", body: "demo") + let skill = fixture.repo.appendingPathComponent("skills/demo") + try FileManager.default.createSymbolicLink( + atPath: skill.appendingPathComponent("here").path, withDestinationPath: ".") + try FileManager.default.createSymbolicLink( + atPath: skill.appendingPathComponent("leak").path, + withDestinationPath: "here/here/../../settings.json") + try fixture.commit() + #expect(throws: CoreError.self) { + try SkillOperations.add( + AddOptions( + source: fixture.repo.path, agents: [.codex], mode: .copy, + environment: fixture.environment)) + } + } + @Test func publicDiscoveryForwardsDepthAndInternalEnvironmentValues() throws { let fixture = try SkillFixture() try fixture.skill("public", body: "public") From 16452c2e925eafcbde53e21aa9732c7f81c1baaf Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Mon, 26 Oct 2026 22:50:58 +0800 Subject: [PATCH 14/18] fix(cache): split link paths at slash bytes and stop before missing parents Splitting a destination into Swift characters let a prepended Unicode mark join a following slash, hiding a separator from validation. Components are now split and compared as UTF-8 bytes. A missing entry ends resolution only when no '..' follows it, because a filesystem that looks names up by case or normalization can resolve that entry to another one in the same directory. --- Sources/AgentsCore/PathSafety.swift | 30 ++++++++++++--------- Tests/AgentsCoreTests/PathSafetyTests.swift | 10 +++++-- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/Sources/AgentsCore/PathSafety.swift b/Sources/AgentsCore/PathSafety.swift index 6a75196..2ac30e7 100644 --- a/Sources/AgentsCore/PathSafety.swift +++ b/Sources/AgentsCore/PathSafety.swift @@ -40,20 +40,23 @@ public enum PathSafety { /// Whether the symbolic link at `link` stays inside the real directory `root` wherever that /// tree is placed. Its destination is resolved from the link's directory as the kernel does, - /// following links inside `root`; the link stays inside when resolution reaches a missing entry, - /// which the tree lacks in any placement, or ends without leaving `root`. An absolute - /// destination, a step above `root` and a link loop leave it. + /// byte by byte and following links inside `root`. An absolute destination, a step above `root` + /// and a link loop leave it. Resolution may stop at a missing entry, since the kernel cannot pass + /// it, but only when no `..` follows: another filesystem may look the name up differently, as + /// another entry of the same directory, which is itself checked. package static func linkStaysInside(_ link: URL, root: String) throws -> Bool { guard let directory = realPath(link.deletingLastPathComponent().path), - directory == root || directory.hasPrefix(root + "/") + directory.utf8.elementsEqual(root.utf8) || directory.utf8.starts(with: (root + "/").utf8) else { return false } - var current = directory.dropFirst(root.count).split(separator: "/").map(String.init) + let relative = directory.utf8.dropFirst(min(root.utf8.count + 1, directory.utf8.count)) + var current = components(String(decoding: relative, as: UTF8.self)).compactMap { $0 } var pending = try components(FileManager.default.destinationOfSymbolicLink(atPath: link.path)) var expansions = 0 + func isParent(_ component: String?) -> Bool { component?.utf8.elementsEqual("..".utf8) == true } while !pending.isEmpty { guard let next = pending.removeFirst() else { return false } - if next == "." { continue } - if next == ".." { + if next.utf8.elementsEqual(".".utf8) { continue } + if isParent(next) { guard current.popLast() != nil else { return false } continue } @@ -64,16 +67,19 @@ public enum PathSafety { pending = components(destination) + pending continue } - guard FileManager.default.fileExists(atPath: path) else { return true } + guard FileManager.default.fileExists(atPath: path) else { + return !pending.contains { $0 == nil || isParent($0) } + } current.append(next) } return true } - /// A relative destination's components; nil marks an absolute destination. - private static func components(_ destination: String) -> [String?] { - guard !destination.hasPrefix("/") else { return [nil] } - return destination.split(separator: "/").map(String.init) + /// A path's components split at `/` bytes, so no Unicode grapheme hides a separator; an + /// absolute path yields a single nil. + private static func components(_ path: String) -> [String?] { + guard path.utf8.first != UInt8(ascii: "/") else { return [nil] } + return path.utf8.split(separator: UInt8(ascii: "/")).map { String(decoding: $0, as: UTF8.self) } } /// The path as the kernel resolves it for a reader, or nil when it does not exist. diff --git a/Tests/AgentsCoreTests/PathSafetyTests.swift b/Tests/AgentsCoreTests/PathSafetyTests.swift index e80f16d..e131b5c 100644 --- a/Tests/AgentsCoreTests/PathSafetyTests.swift +++ b/Tests/AgentsCoreTests/PathSafetyTests.swift @@ -16,7 +16,9 @@ struct PathSafetyAndSanitizationTests { let links = [ "here": ".", "leak": "here/here/../../settings.json", "guide": "here/docs/guide.md", "pdf": "../../library/missing.pdf", "up": "../../../outside", "absolute": "/etc/hosts", - "loop": "loop-back", "loop-back": "loop", + "loop": "loop-back", "loop-back": "loop", "here\u{0600}": ".", + "unicode": "here\u{0600}/../../settings.json", "case": "HERE/HERE/../../settings.json", + "missing-up": "missing/../docs/guide.md", ] for (name, destination) in links { try FileManager.default.createSymbolicLink( @@ -27,7 +29,11 @@ struct PathSafetyAndSanitizationTests { skill.appendingPathComponent(name), root: try #require(PathSafety.realPath(base.path))) } for name in ["here", "guide"] { #expect(try stays(name, in: skill)) } - for name in ["leak", "pdf", "up", "absolute", "loop"] { #expect(try !stays(name, in: skill)) } + // A grapheme cannot hide a separator, and a lookup that differs by case or normalization on + // another filesystem cannot turn a missing entry into a step above the root. + for name in ["leak", "pdf", "up", "absolute", "loop", "unicode", "case", "missing-up"] { + #expect(try !stays(name, in: skill)) + } // In the whole repository, the same dangling links stay inside and cannot be followed out. for name in ["leak", "pdf"] { #expect(try stays(name, in: repo)) } #expect(try !stays("up", in: repo)) From a97e3db8ecd58faa08183b17719a20954cd74c83 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:09:09 +0800 Subject: [PATCH 15/18] feat(state): write the declaration and lock in Prettier's JSON layout agents.json and agents.resolved were written in Foundation's layout, which `prettier --check` rejects. They now use Prettier's default layout: two-space indentation, "key": value, expanded objects, {} and [] for empty containers, and arrays on one line when they fit in 80 columns. Any operation that writes state rewrites a file in another layout even when its content is unchanged. Empty lock sections stay because skill 0.3.1 requires them; journals, watch state and content hashes keep the encoder's fixed bytes. This repository's own state is rewritten. --- .agent/agents.json | 19 +-- .agent/agents.resolved | 71 ++++---- CHANGELOG.md | 10 +- Documentation/Architecture/State.md | 15 +- Documentation/Proposals/AgentInstructions.md | 5 +- Sources/AgentsCore/StateJSON.swift | 156 ++++++++++++++++++ Sources/AgentsCore/StateStore.swift | 22 ++- .../InstructionOperations.swift | 4 +- Sources/AgentsSkills/SkillLifecycle.swift | 2 +- Sources/AgentsSkills/SkillOperations.swift | 2 +- Sources/AgentsUpdates/UpdatePlan.swift | 2 +- Tests/AgentsCoreTests/StateJSONTests.swift | 59 +++++++ Tests/AgentsCoreTests/StateModelTests.swift | 2 +- .../TargetLifecycleTests.swift | 33 ++-- 14 files changed, 320 insertions(+), 82 deletions(-) create mode 100644 Sources/AgentsCore/StateJSON.swift create mode 100644 Tests/AgentsCoreTests/StateJSONTests.swift diff --git a/.agent/agents.json b/.agent/agents.json index b01d82e..90bd0e7 100644 --- a/.agent/agents.json +++ b/.agent/agents.json @@ -1,20 +1,17 @@ { - "sources": { - "agents-tools": { - "git": "github.com/agents-tools/.github", - "path": ".agent", - "revision": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6" - } - }, "instructions": { - "agents": [ - "claude-code", - "codex" - ], + "agents": ["claude-code", "codex"], "sections": [ "guide", "agents-tools:shared/swift-package-route", "agents-tools:shared/swift-package-tests" ] + }, + "sources": { + "agents-tools": { + "git": "github.com/agents-tools/.github", + "path": ".agent", + "revision": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6" + } } } diff --git a/.agent/agents.resolved b/.agent/agents.resolved index 3223faa..9bb6ccf 100644 --- a/.agent/agents.resolved +++ b/.agent/agents.resolved @@ -1,54 +1,47 @@ { - "instructions" : { - "chatgpt" : { - - }, - "sections" : [ + "instructions": { + "chatgpt": {}, + "sections": [ { - "hash" : "sha256:b954b104c6cf0639214a105a846d4fc8e73fd55f14eb695f407f942b905bf22e", - "name" : "guide", - "path" : ".agent/instructions/guide.md", - "source" : "." + "hash": "sha256:b954b104c6cf0639214a105a846d4fc8e73fd55f14eb695f407f942b905bf22e", + "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" : "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6", - "source" : "github.com/agents-tools/.github" + "hash": "sha256:a45b15d662eecec4b252fa2e35a608bab0ee137fae525669097f45d0f8c3f39d", + "name": "shared/swift-package-route", + "path": ".agent/instructions/shared/swift-package-route.md", + "revision": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6", + "source": "github.com/agents-tools/.github" }, { - "hash" : "sha256:5d9f40d101938d2805482b9a147397bc07e9c3c9223cfe040f0905cb6c746825", - "name" : "shared/swift-package-tests", - "path" : ".agent/instructions/shared/swift-package-tests.md", - "revision" : "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6", - "source" : "github.com/agents-tools/.github" + "hash": "sha256:5d9f40d101938d2805482b9a147397bc07e9c3c9223cfe040f0905cb6c746825", + "name": "shared/swift-package-tests", + "path": ".agent/instructions/shared/swift-package-tests.md", + "revision": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6", + "source": "github.com/agents-tools/.github" } ], - "targets" : { - "AGENTS.md" : { - "agents" : [ - "claude-code", - "codex" - ], - "blockHash" : "sha256:a025a4ce7d403ace72e30ffe5b2922f571c44f0f6ea52998f5a1bfe6a7ee3fd6", - "created" : false, - "headingOffset" : 0 + "targets": { + "AGENTS.md": { + "agents": ["claude-code", "codex"], + "blockHash": "sha256:a025a4ce7d403ace72e30ffe5b2922f571c44f0f6ea52998f5a1bfe6a7ee3fd6", + "created": false, + "headingOffset": 0 } } }, - "skills" : { - - }, - "sources" : { - "github.com/agents-tools/.github" : { - "kind" : "git", - "path" : ".agent", - "requirement" : { - "revision" : "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6" + "skills": {}, + "sources": { + "github.com/agents-tools/.github": { + "kind": "git", + "path": ".agent", + "requirement": { + "revision": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6" }, - "url" : "https://github.com/agents-tools/.github" + "url": "https://github.com/agents-tools/.github" } }, - "version" : 1 + "version": 1 } diff --git a/CHANGELOG.md b/CHANGELOG.md index 3569f95..195d2aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -43,9 +43,13 @@ publication follows the [release checklist](Documentation/Reference/Release.md). `initializeInstructions(named:directory:)` and creates `.agent/instructions/.md` in the project, using the project's state lock. -- A declaration may omit `sources`. Operations that leave a declaration's - content unchanged no longer rewrite `agents.json`, so a committed - declaration keeps its formatting. +- A declaration may omit `sources`. +- `agents.json` and `agents.resolved` are written in Prettier's default JSON + layout: two-space indentation, `"key": value`, expanded objects, empty + containers as `{}` and `[]`, and an array on one line when it fits in 80 + columns. Any operation that writes state rewrites a file in another layout, + such as the one earlier versions wrote, even when its content is unchanged. + Empty lock sections remain so earlier readers decode the lock. - A local link in a section must resolve, from the target, to a file in the checkout being written; user targets accept no local links. - Removing a name that equals a declared reference removes that reference, so diff --git a/Documentation/Architecture/State.md b/Documentation/Architecture/State.md index 568c24a..262c834 100644 --- a/Documentation/Architecture/State.md +++ b/Documentation/Architecture/State.md @@ -20,9 +20,18 @@ location, an optional requirement, and an optional search `path`. A source added by location keeps the alias already declaring it, or receives its location's last path component; while another source holds that name, preceding components are prefixed (`anthropics-skills`), then a number is appended. `sources` may be -omitted. An operation writes `agents.json`, in normalized form, only when it -changes the declaration's content, so a hand-written declaration keeps its -formatting otherwise. +omitted. + +`agents.json` and `agents.resolved` are written with sorted keys in Prettier's +default JSON layout: two-space indentation, `"key": value`, every non-empty +object expanded, empty containers as `{}` and `[]`, and an array without objects +on one line when it fits in 80 columns. A repository whose Prettier +configuration uses another print width may lay out an array between the two +widths differently. An operation that writes state rewrites either file when +its bytes differ from that layout, even when its content is unchanged. Empty +lock sections such as `"skills": {}` remain, because earlier readers require +them. Journals, `agents.watch` and content hashes keep the encoder's fixed +layout. ```json { diff --git a/Documentation/Proposals/AgentInstructions.md b/Documentation/Proposals/AgentInstructions.md index 47351ee..3588242 100644 --- a/Documentation/Proposals/AgentInstructions.md +++ b/Documentation/Proposals/AgentInstructions.md @@ -355,8 +355,9 @@ Commands edit the declaration; editing it by hand is possible. each pin. A pin that cannot be fetched, content whose digest does not match, or an own instructions file whose hash changed since the lock is an error, never a substitution. -- Output is sorted, except section order, and has no timestamps. Writes take a - file lock and replace the file atomically. +- Output is sorted, except section order, and has no timestamps. The declaration + and lock use Prettier's default JSON layout. Writes take a file lock and + replace the file atomically. ### Watch State diff --git a/Sources/AgentsCore/StateJSON.swift b/Sources/AgentsCore/StateJSON.swift new file mode 100644 index 0000000..4ecd595 --- /dev/null +++ b/Sources/AgentsCore/StateJSON.swift @@ -0,0 +1,156 @@ +import Foundation + +/// The layout of `agents.json` and `agents.resolved`, as Prettier writes JSON with its default +/// 80-column width: two-space indentation, `"key": value`, every non-empty object expanded one +/// member per line, empty containers as `{}` and `[]`, and an array on one line when it holds no +/// object and fits, else one element per line. Keys keep the encoder's sorted order and string +/// bytes are copied as encoded. +enum StateJSON { + private static let width = 80 + + private indirect enum Node { + case object([(key: String, value: Node)]) + case array([Node]) + case scalar(String) + } + + /// Lays out the compact JSON that `JSONEncoder` produced, ending with a newline. + static func format(_ compact: Data) throws -> Data { + var parser = Parser(bytes: Array(compact)) + let node = try parser.value() + parser.skipWhitespace() + guard parser.index == parser.bytes.count else { throw CoreError.invalidState("invalid JSON") } + return Data((render(node, depth: 0, column: 0, trailing: 0) + "\n").utf8) + } + + /// `column` is where the value starts; `trailing` counts the characters after it on its line. + private static func render(_ node: Node, depth: Int, column: Int, trailing: Int) -> String { + let indent = String(repeating: " ", count: depth + 1) + let closing = String(repeating: " ", count: depth) + switch node { + case .scalar(let text): + return text + case .object(let members): + guard !members.isEmpty else { return "{}" } + let lines = members.enumerated().map { offset, member in + let prefix = indent + member.key + ": " + let comma = offset < members.count - 1 ? "," : "" + return prefix + + render( + member.value, depth: depth + 1, column: prefix.count, trailing: comma.count) + comma + } + return "{\n" + lines.joined(separator: "\n") + "\n" + closing + "}" + case .array(let elements): + guard !elements.isEmpty else { return "[]" } + if let flat = flat(node), column + flat.count + trailing <= width { return flat } + let lines = elements.enumerated().map { offset, element in + let comma = offset < elements.count - 1 ? "," : "" + return indent + + render(element, depth: depth + 1, column: indent.count, trailing: comma.count) + comma + } + return "[\n" + lines.joined(separator: "\n") + "\n" + closing + "]" + } + } + + /// The one-line form of an array without objects, or nil when it holds one. + private static func flat(_ node: Node) -> String? { + switch node { + case .scalar(let text): return text + case .object(let members): return members.isEmpty ? "{}" : nil + case .array(let elements): + var parts: [String] = [] + for element in elements { + guard let part = flat(element) else { return nil } + parts.append(part) + } + return "[" + parts.joined(separator: ", ") + "]" + } + } + + private struct Parser { + let bytes: [UInt8] + var index = 0 + + mutating func skipWhitespace() { + while index < bytes.count, [9, 10, 13, 32].contains(bytes[index]) { index += 1 } + } + + mutating func value() throws -> Node { + skipWhitespace() + guard index < bytes.count else { throw CoreError.invalidState("invalid JSON") } + switch bytes[index] { + case UInt8(ascii: "{"): + index += 1 + var members: [(key: String, value: Node)] = [] + skipWhitespace() + if index < bytes.count, bytes[index] == UInt8(ascii: "}") { + index += 1 + return .object(members) + } + while true { + skipWhitespace() + let key = try string() + skipWhitespace() + try expect(UInt8(ascii: ":")) + members.append((key, try value())) + skipWhitespace() + if try separatorEnds(UInt8(ascii: "}")) { return .object(members) } + } + case UInt8(ascii: "["): + index += 1 + var elements: [Node] = [] + skipWhitespace() + if index < bytes.count, bytes[index] == UInt8(ascii: "]") { + index += 1 + return .array(elements) + } + while true { + elements.append(try value()) + skipWhitespace() + if try separatorEnds(UInt8(ascii: "]")) { return .array(elements) } + } + case UInt8(ascii: "\""): + return .scalar(try string()) + default: + let start = index + while index < bytes.count, + ![UInt8(ascii: ","), UInt8(ascii: "]"), UInt8(ascii: "}"), 9, 10, 13, 32].contains( + bytes[index]) + { + index += 1 + } + guard index > start else { throw CoreError.invalidState("invalid JSON") } + return .scalar(String(decoding: bytes[start.. String { + try expect(UInt8(ascii: "\"")) + let start = index - 1 + while index < bytes.count, bytes[index] != UInt8(ascii: "\"") { + index += bytes[index] == UInt8(ascii: "\\") ? 2 : 1 + } + try expect(UInt8(ascii: "\"")) + return String(decoding: bytes[start.. Bool { + guard index < bytes.count else { throw CoreError.invalidState("invalid JSON") } + if bytes[index] == UInt8(ascii: ",") { + index += 1 + return false + } + try expect(close) + return true + } + + mutating func expect(_ byte: UInt8) throws { + guard index < bytes.count, bytes[index] == byte else { + throw CoreError.invalidState("invalid JSON") + } + index += 1 + } + } +} diff --git a/Sources/AgentsCore/StateStore.swift b/Sources/AgentsCore/StateStore.swift index 7ebb928..f2cd90e 100644 --- a/Sources/AgentsCore/StateStore.swift +++ b/Sources/AgentsCore/StateStore.swift @@ -62,7 +62,8 @@ public struct StateStore: Sendable { _ = try readResolved() let transaction = FileTransaction(store: self) try stageDeclaration(declaration, in: transaction) - try transaction.replace(resolvedURL, content: nil, data: Self.encode(resolved.normalized)) + try transaction.replace( + resolvedURL, content: nil, data: Self.encodeState(resolved.normalized)) if let watch { try transaction.replace(watchURL, content: nil, data: Self.encode(watch)) } @@ -70,13 +71,13 @@ public struct StateStore: Sendable { } } - /// Stages the declaration only when its content differs from the file's, so a declaration - /// whose content an operation leaves unchanged keeps its author's formatting. + /// Stages the declaration when the file's bytes differ from its standard layout, so a file + /// written by hand or by an earlier version is rewritten even when its content is unchanged. package func stageDeclaration(_ declaration: Declaration, in transaction: FileTransaction) throws { - let current: Declaration? = try load(declarationURL) - guard current?.normalized != declaration.normalized else { return } - try transaction.replace(declarationURL, content: nil, data: Self.encode(declaration.normalized)) + let data = try Self.encodeState(declaration.normalized) + guard try existingData(declarationURL) != data else { return } + try transaction.replace(declarationURL, content: nil, data: data) } package func withLock( @@ -136,6 +137,15 @@ public struct StateStore: Sendable { return try parent.child(name) } + /// Encodes `agents.json` or `agents.resolved` in the layout `StateJSON` describes. + package static func encodeState(_ value: T) throws -> Data { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return try StateJSON.format(encoder.encode(value)) + } + + /// Encodes journals, watch state and content hashes. Its bytes feed recorded hashes, so its + /// layout stays fixed. package static func encode(_ value: T) throws -> Data { let encoder = JSONEncoder() encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes] diff --git a/Sources/AgentsInstructions/InstructionOperations.swift b/Sources/AgentsInstructions/InstructionOperations.swift index 493d824..55a94dc 100644 --- a/Sources/AgentsInstructions/InstructionOperations.swift +++ b/Sources/AgentsInstructions/InstructionOperations.swift @@ -169,7 +169,7 @@ public enum InstructionOperations { try plan.stage(transaction: transaction) try store.stageDeclaration(declaration, in: transaction) try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encode(plan.next.normalized)) + store.resolvedURL, content: nil, data: StateStore.encodeState(plan.next.normalized)) try SourceCache(store: store).prune(referencedBy: plan.next, transaction: transaction) try transaction.commit() } @@ -433,7 +433,7 @@ public enum InstructionOperations { if writeState { try store.stageDeclaration(declaration, in: transaction) try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encode(next.normalized)) + store.resolvedURL, content: nil, data: StateStore.encodeState(next.normalized)) } try sources.cache.prune(referencedBy: next, transaction: transaction) try transaction.commit() diff --git a/Sources/AgentsSkills/SkillLifecycle.swift b/Sources/AgentsSkills/SkillLifecycle.swift index 24ba425..84efc55 100644 --- a/Sources/AgentsSkills/SkillLifecycle.swift +++ b/Sources/AgentsSkills/SkillLifecycle.swift @@ -223,7 +223,7 @@ final class SkillLifecycle { if writeState { try store.stageDeclaration(declaration, in: transaction) try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encode(next.normalized)) + store.resolvedURL, content: nil, data: StateStore.encodeState(next.normalized)) } try cache.prune(referencedBy: next, transaction: transaction) try transaction.commit() diff --git a/Sources/AgentsSkills/SkillOperations.swift b/Sources/AgentsSkills/SkillOperations.swift index 552d2d0..8523e51 100644 --- a/Sources/AgentsSkills/SkillOperations.swift +++ b/Sources/AgentsSkills/SkillOperations.swift @@ -161,7 +161,7 @@ public enum SkillOperations { try plan.stage(retained: retained, transaction: transaction) try store.stageDeclaration(declaration, in: transaction) try transaction.replace( - store.resolvedURL, content: nil, data: StateStore.encode(plan.next.normalized)) + store.resolvedURL, content: nil, data: StateStore.encodeState(plan.next.normalized)) try SourceCache(store: store).prune(referencedBy: plan.next, transaction: transaction) try transaction.commit() let installed = plan.receipts diff --git a/Sources/AgentsUpdates/UpdatePlan.swift b/Sources/AgentsUpdates/UpdatePlan.swift index 775f159..8873eb8 100644 --- a/Sources/AgentsUpdates/UpdatePlan.swift +++ b/Sources/AgentsUpdates/UpdatePlan.swift @@ -81,7 +81,7 @@ final class UpdatePlan { try skills.stage(retained: retained, transaction: transaction) try instructions.stage(transaction: transaction) try store.stageDeclaration(declaration, in: transaction) - let resolvedBytes = try StateStore.encode(next.normalized) + let resolvedBytes = try StateStore.encodeState(next.normalized) if try store.existingData(store.resolvedURL) != resolvedBytes { try transaction.replace(store.resolvedURL, content: nil, data: resolvedBytes) } diff --git a/Tests/AgentsCoreTests/StateJSONTests.swift b/Tests/AgentsCoreTests/StateJSONTests.swift new file mode 100644 index 0000000..78009e2 --- /dev/null +++ b/Tests/AgentsCoreTests/StateJSONTests.swift @@ -0,0 +1,59 @@ +import Foundation +import Testing + +@testable import AgentsCore + +@Suite("State file layout") +struct StateJSONTests { + private func layout(_ compact: String) throws -> String { + String(decoding: try StateJSON.format(Data(compact.utf8)), as: UTF8.self) + } + + @Test func expandsObjectsAndKeepsShortScalarArraysOnOneLine() throws { + let compact = """ + {"instructions":{"agents":["claude-code","codex"],"chatgpt":{},"sections":["guide","agents-tools:shared/swift-package-route","agents-tools:shared/swift-package-tests"]},"nested":[{"a":1},{"b":[]}],"skills":{},"text":"x : y \\"q\\" \\\\ é"} + """ + #expect( + try layout(compact) == """ + { + "instructions": { + "agents": ["claude-code", "codex"], + "chatgpt": {}, + "sections": [ + "guide", + "agents-tools:shared/swift-package-route", + "agents-tools:shared/swift-package-tests" + ] + }, + "nested": [ + { + "a": 1 + }, + { + "b": [] + } + ], + "skills": {}, + "text": "x : y \\"q\\" \\\\ é" + } + + """) + } + + @Test func breaksAnArrayOnlyPastEightyColumnsIncludingItsComma() throws { + // ` "k": [...]` with one element whose quoted text fills the rest of the line. + func array(_ length: Int, comma: Bool) throws -> String { + let element = String(repeating: "a", count: length) + let compact = "{\"k\":[\"\(element)\"]" + (comma ? ",\"z\":0}" : "}") + return try layout(compact).split(separator: "\n")[1].description + } + // ` "k": ` ends at column 7 and `["…"]` adds four characters: Prettier keeps 69 characters + // on the line, or 68 when a comma follows. + #expect(try array(69, comma: false).hasSuffix("\"]")) + #expect(try array(70, comma: false) == " \"k\": [") + #expect(try array(68, comma: true).hasSuffix("\"],")) + #expect(try array(69, comma: true) == " \"k\": [") + #expect(try layout("{}") == "{}\n") + #expect(try layout("[]") == "[]\n") + } +} diff --git a/Tests/AgentsCoreTests/StateModelTests.swift b/Tests/AgentsCoreTests/StateModelTests.swift index 05758e2..5dc05c5 100644 --- a/Tests/AgentsCoreTests/StateModelTests.swift +++ b/Tests/AgentsCoreTests/StateModelTests.swift @@ -99,7 +99,7 @@ struct StateModelTests { #expect(try Data(contentsOf: store.declarationURL) == firstDeclaration) #expect(try store.loadDeclaration() == declaration) #expect(try store.loadResolved() == lock) - #expect(String(decoding: first, as: UTF8.self).contains("\"from\" : \"1.0.0\"")) + #expect(String(decoding: first, as: UTF8.self).contains("\"from\": \"1.0.0\"")) } @Test func rejectsCorruptionWithoutReplacingFiles() throws { diff --git a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift index a4d54a7..392fe1c 100644 --- a/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift +++ b/Tests/AgentsInstructionsTests/TargetLifecycleTests.swift @@ -45,21 +45,30 @@ struct TargetLifecycleTests { }) } - @Test func updatesKeepADeclarationWhoseContentIsUnchanged() throws { + @Test func updateApplyWritesStateInTheStandardLayout() throws { let fixture = try InstructionFixture() try fixture.own("guide") - let declaration = - "{\n \"instructions\": {\"agents\": [\"codex\"], \"sections\": [\"guide\"]}\n}\n" - let file = fixture.store().declarationURL - try fixture.write(declaration, to: file) - _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) - #expect(try String(contentsOf: file, encoding: .utf8) == declaration) - #expect(try fixture.text() == generated(["# guide\n\nOriginal"])) - _ = try InstructionOperations.updateInstalled( - agents: [.codex, .geminiCLI], environment: fixture.environment, apply: true) + try fixture.addOwn(names: ["guide"], agents: [.codex]) + let declarationFile = fixture.store().declarationURL + let lockFile = fixture.store().resolvedURL + let declaration = try Data(contentsOf: declarationFile) + let lock = try Data(contentsOf: lockFile) #expect( - try fixture.store().loadDeclaration().instructions?.agents == [.codex, .geminiCLI]) - #expect(try String(contentsOf: file, encoding: .utf8) != declaration) + String(decoding: declaration, as: UTF8.self) + == "{\n \"instructions\": {\n \"agents\": [\"codex\"],\n \"sections\": [\"guide\"]\n },\n \"sources\": {}\n}\n" + ) + let lockText = String(decoding: lock, as: UTF8.self) + #expect(lockText.contains("\"chatgpt\": {}") && lockText.contains("\"skills\": {}")) + #expect(!lockText.contains(" : ")) + // An earlier version wrote this content in Foundation's layout. + try StateStore.encode(fixture.store().loadDeclaration()).write(to: declarationFile) + try StateStore.encode(fixture.store().loadResolved()).write(to: lockFile) + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try Data(contentsOf: declarationFile) == declaration) + #expect(try Data(contentsOf: lockFile) == lock) + _ = try InstructionOperations.updateInstalled(environment: fixture.environment, apply: true) + #expect(try Data(contentsOf: declarationFile) == declaration) + #expect(try Data(contentsOf: lockFile) == lock) } @Test func pathsPlaceSectionsInNestedTargets() throws { From 89b38807b4e8552b9fbfe65ad845f8fcbfe09ccd Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:15:35 +0800 Subject: [PATCH 16/18] ci: pin shared workflows to the merged instruction files policy --- .github/workflows/ci.yml | 2 +- .github/workflows/source-policy.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c3d22cc..dd0d3cf 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@d0d1fd91e655e6d230cf3d5085c1eb6f5f26d358 + 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 b907378..bb2db02 100644 --- a/.github/workflows/source-policy.yml +++ b/.github/workflows/source-policy.yml @@ -17,7 +17,7 @@ concurrency: jobs: policy: if: github.event_name != 'push' || !github.event.deleted - uses: agents-tools/github-workflows/.github/workflows/policy.yml@d0d1fd91e655e6d230cf3d5085c1eb6f5f26d358 + uses: agents-tools/github-workflows/.github/workflows/policy.yml@bb0a8c8c39827a364b9d3cbf4069754e7d975586 with: allow-terms: | ChatGPT From c463c12bd9c0019da94a1b2bf0175acd453ec972 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:15:35 +0800 Subject: [PATCH 17/18] chore(release): prepare 0.2.0 --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 195d2aa..977f5cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,8 @@ publication follows the [release checklist](Documentation/Reference/Release.md). ## Unreleased +## 0.2.0 - 2026-10-27 + ### Added - Instructions files may sit in subdirectories of `instructions/` and From 8df88c29dfabadbc01cad3b6fad19b2b8aa09b99 Mon Sep 17 00:00:00 2001 From: showxu <10173746+showxu@users.noreply.github.com> Date: Tue, 27 Oct 2026 02:25:30 +0800 Subject: [PATCH 18/18] docs: follow the organization standard's default branch --- .agent/agents.json | 4 ++-- .agent/agents.resolved | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.agent/agents.json b/.agent/agents.json index 90bd0e7..5c68742 100644 --- a/.agent/agents.json +++ b/.agent/agents.json @@ -9,9 +9,9 @@ }, "sources": { "agents-tools": { + "branch": "master", "git": "github.com/agents-tools/.github", - "path": ".agent", - "revision": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6" + "path": ".agent" } } } diff --git a/.agent/agents.resolved b/.agent/agents.resolved index 9bb6ccf..24e08d3 100644 --- a/.agent/agents.resolved +++ b/.agent/agents.resolved @@ -12,14 +12,14 @@ "hash": "sha256:a45b15d662eecec4b252fa2e35a608bab0ee137fae525669097f45d0f8c3f39d", "name": "shared/swift-package-route", "path": ".agent/instructions/shared/swift-package-route.md", - "revision": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6", + "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": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6", + "revision": "fc8a2fc1b9d5dcea39788d0c70cd35dded2673ea", "source": "github.com/agents-tools/.github" } ], @@ -38,7 +38,7 @@ "kind": "git", "path": ".agent", "requirement": { - "revision": "6c0f3fe6f1400e230dea9e3e21a59362df2ec9a6" + "branch": "master" }, "url": "https://github.com/agents-tools/.github" }